9

how do i detect and move to the next line using std::ifstream?

void readData(ifstream& in)
{
    string sz;
    getline(in, sz);
    cout << sz <<endl;
    int v;
    for(int i=0; in.good(); i++)
    {
        in >> v;
        if (in.good())
            cout << v << " ";
    }
    in.seekg(0, ios::beg);
    sz.clear();
    getline(in, sz);
    cout << sz <<endl; //no longer reads
}

I know good would tell me if an error happened but the stream no longer works once that happens. How can i check to see if i am at the end of line before reading another int?

2 Answers2

20

Use ignore() to ignore everything until the next line:

 in.ignore(std::numeric_limits<std::streamsize>::max(), '\n')

If you must do it manually just check othe character to see if is '\n'

char next;
while(in.get(next))
{
    if (next == '\n')  // If the file has been opened in
    {    break;        // text mode then it will correctly decode the
    }                  // platform specific EOL marker into '\n'
}
// This is reached on a newline or EOF

This is probably failing because you are doing a seek before clearing the bad bits.

in.seekg(0, ios::beg);    // If bad bits. Is this not ignored ?
                          // So this is not moving the file position.
sz.clear();
getline(in, sz);
cout << sz <<endl; //no longer reads
Martin York
  • 257,169
  • 86
  • 333
  • 562
3

You should clear the error state of the stream with in.clear(); after the loop, then the stream will work again as if no error happened.

You might also simplify your loop to:

while (in >> v) {
  cout << v << " ";
}
in.clear();

The stream extraction returns if the operation succeeded, so you can test this directly without explicitly checking in.good();.

sth
  • 222,467
  • 53
  • 283
  • 367
  • It is possible for a valid int to be followed immediately by the end-of-file. To consider parsing this as a success you need to check in.fail() for false, as in.good() will return false if the end of file is reached even if the extraction operation succeeded. – CB Bailey Jan 25 '09 at 09:55
  • @Charles: The implicit `operator void*` calls `fail`, so `while (in >> v)` will succeed if extraction succeed, regardless if EOF state. – dalle Jan 25 '09 at 10:40
  • @dalle, yes I know that, this is what makes the while loop work 'as expected'. I was just commenting because sth compared explicitly checking 'in.good()' with using the 'while (in >>v)' idiom and wanted to note that they are not equivalent. – CB Bailey Jan 25 '09 at 11:07