Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't in.good() the same as !in.fail()?

Tags:

c++

I've read that the following is an anti-pattern:

while(in.good()) {
    // ...
}

But this is preferred:

while(operation) {
}

However, the stream has a conversion operator to bool that returns !fail(). Isn't !fail() the same as good()? If not, why aren't these two functions symmetrical? I'd expect it to be similar to true == !false.

like image 549
user5380624 Avatar asked Sep 27 '15 02:09

user5380624


Video Answer


1 Answers

There's an excellent table at http://en.cppreference.com/w/cpp/io/basic_ios/good that explains state of an std::istream and the values various functions return.

The only time while ( stream.good() ) and while(stream) will be different is when the contents of stream have been successfully read and EOF has been reached. At that time, stream.good() returns true while (bool)stream evaluates to false.

like image 125
R Sahu Avatar answered Oct 06 '22 15:10

R Sahu