Testing stream.good () or! Stream.eof () reads the last line twice

Possible duplicate:
Why is iostream :: eof inside a loop condition considered wrong?

I have the following code snippet:

ifstream f("x.txt"); string line; while (f.good()) { getline(f, line); // Use line here. } 

But it reads the last line twice. Why is this happening and how to fix it?

Something very similar happens to:

 ifstream f("x.txt"); string line; while (!f.eof()) { getline(f, line); // Use line here. } 
+16
c ++ iostream
Dec 01 '10 at
source share
3 answers

You very, very rarely want to check for bad, effective and good. In particular, for eof (as! Stream.eof () is a common mistake), the stream flowing in EOF does not necessarily mean that the last input operation failed; conversely, not in EOF does not mean that the last entry was successful.

All stream state functions — fail, bad, eof, and good — tell you the current state of the stream, rather than predicting the success of a future operation. Check the current thread (which is equivalent to checking with inverted failure) after the desired operation:

 if (getline(stream, line)) { use(line); } else { handle_error(); } if (stream >> foo >> bar) { use(foo, bar); } else { handle_error(); } if (!(stream >> foo)) { // operator! is overloaded for streams throw SomeException(); } use(foo); 

To read and process all lines:

 for (std::string line; getline(stream, line);) { process(line); } 

Precisely speaking, good () is incorrectly named and is not equivalent to testing the stream itself (as can be seen from the above examples).

+30
Dec 01 '10 at 1:09 p.m.
source share

Just use

 ifstream f("x.txt"); while (getline(f, line)) { // whatever } 

This is an idiomatic way to write such a loop. I could not reproduce the error (on a Linux machine).

+8
Dec 01 '10 at 12:45
source share

He did not read the last line twice, but since it was not read when it reached the eof level, your line of the line has the same value as before.

This is because f is no longer “good” when he read EOF, and not when he is going to read it.

+1
Dec 01 '10 at
source share



All Articles