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)) {
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).
Fred Nurk Dec 01 '10 at 1:09 p.m. 2010-12-01 13:09
source share