0
votes

I know that we can use std::cin as a condition, for example, in

while (std::cin >> value)

using std::cin as a condition will call a member function std::ios::operator bool. It says that it "returns whether an error flag is set (either failbit or badbit)", which does not include eofbit. Despite this, passing end-of-file (by Ctrl+d) terminates the loop. Why? Can failbit or badbit also set an eofbit?

I also found this explanation, but in C++ Reference it specifically says that "this function does not return the same as member good"

1
Eofbit isn't really an error flag. It tells you why an error occurred -- input failed (so failbit was set) because the read attempt hit the end of the file before seeing a valid text sequence.Pete Becker

1 Answers

1
votes

The loop above does not test for end of file. It tests for failure to read a value, end of file is just one possible cause of this. Even end of file does not necessarily cause a failure to read a value, imagine reading an integer where the digits are terminated by the end of file, you still read an integer even though you hit the end of file.

The bottom line is that failure to read a value for any reason sets the fail bit, and this loop tests for that.