-
November 28th, 2012, 02:42 PM
#1
Grab special lines from a file
Hello
I have a file that contain different content, some lines inside that file looks like that :
Time : xx:xx:xx
Time : xx:xx:xx
So, I want to grab lines that start with "Time : " and put them inside a list<string> for later use. I am using windows so I don't know if the newline character is '\n' or '\r' also I don't want my grabed line contain any special character.
I have this code, but didn't work well because some special characters remain inside the string.
Code:
string buf;
list<string> ls;
ifstream read("test.txt", ios_base::binary);
while(!read.eof())
{
getline(read,buf,'\n');
if(buf[0]=='T' && buf[1]=='i' && buf[2]=='m' && buf[3]=='e')
{
ls.push_back(buf);
}
}
-
November 28th, 2012, 10:32 PM
#2
Re: Grab special lines from a file
1) What special characters are in the line ? You can use
the "erase-remove_if" method to get rid of them.
2) Try opening in text mode instead of binary mode.
3) If your line has less than 4 characters, you will access invalid
array indices. You are also looping thru the loop once too often.
You could write the loop:
Code:
while (getline(read,buf))
{
if (buf.substr(0,4) == "Time")
{
ls.push_back(buf);
}
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|