CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Nov 2012
    Posts
    4

    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);
          }
    }

  2. #2
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    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
  •  





Click Here to Expand Forum to Full Width

Featured