Search code examples
c++c++11while-loopiostreamflags

C++: end-of-file interpretation when using std::cin as a condition


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"


Solution

  • 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.