8

I am currently learning C++ from the C++ Primer 5th edition. I am confused about the behavior of the methods to check the status of a stream due to seemingly conflicting information. On page 312 it states

If any of badbit, failbit, or eofbit are set, then a condition that evaluates that stream will fail.

On the very next page, it says that s.fail() is

true if failbit or badbit in the stream is set

and that

the code that is executed when we use a stream as a condition is equivalent to calling !fail().

This doesn't make sense because any expression that uses fail() should only know about failbit and badbit (since those are what make up fail()'s value) and yet !fail() is equivalent to all three of badbit, failbit, and eofbit being false.

How do these seemingly contradictory statements fit together?

hyde
  • 60,639
  • 21
  • 115
  • 176
john01dav
  • 1,842
  • 1
  • 21
  • 40

1 Answers1

3

The second and third statements are correct and in agreement with the C++ standard. The first one, then, is simply a mistake. Neither fail nor operator bool nor operator ! take into account the eofbit state of a stream. Only good and eof do.

In the usual course of events, trying to read past the end of the stream sets both the eofbit and failbit, which is one likely reason why this mistake was so easy to make.

hobbs
  • 223,387
  • 19
  • 210
  • 288
  • If `operator bool` does not check eof, then why does [this](https://pastebin.com/gRERFBiS) program seem to exit the while loop when typing ctrl+d on a Linux system? Does ctrl+d also invalidate stdin? – john01dav Mar 29 '17 at 05:22
  • Because when it doesn't have any more characters to extract it sets the `failbit`. See http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt2 – Dustin Nieffenegger Mar 29 '17 at 05:26
  • See the second paragraph of my answer — the attempt to read using `>>` after EOF causes the stream to be failed *as well as* EOF, so the boolean check returns false. – hobbs Mar 29 '17 at 05:26