I gave an answer which I wanted to check the validity of stream each time through a loop here.
My original code used good
and looked similar to this:
They were wrong. The mantra is 'never test .eof()
'.
Even that mantra is overboard, because both are useful to diagnose the state of the stream after an extraction failed.
So the mantra should be more like
Don't use
good()
oreof()
to detect eof before you try to read any further
Same for fail()
, and bad()
Of course stream.good
can be usefully employed before using a stream (e.g. in case the stream is a filestream which has not been successfully opened)
However, both are very very very often abused to detect the end of input, and that's not how it works.
A canonical example of why you shouldn't use this method:
std::istringstream stream("a");
char ch;
if (stream >> ch) {
std::cout << "At eof? " << std::boolalpha << stream.eof() << "\n";
std::cout << "good? " << std::boolalpha << stream.good() << "\n";
}
Prints
false
true
See it Live On Coliru