template boy
template boy

Reputation: 10480

Are these two conditions equivalent?

Doing input operations before the stream is returned is an idiomatic C++ technique. It looks something like this:

while (in >> var)

or

while (std::getline(in, line))

But when these two functions return, they return a reference to the stream, which results in something like this:

while (in)

Then operator bool() is invoked which checks !fail(). This is my question. Since !fail() only checks failbit or badbit and not eofbit, then how is this safe? Can't the eofbit be set in the stream without either failbit or badbit set and the condition still pass?

For example, the following works:

is.setstate(ios_base::eofbit);

if (is)
    std::cout << "It works";

Upvotes: 0

Views: 50

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103703

If you reach the end of the file, eofbit is set. If eofbit is set, and a read operation is attempted, failbit is set. Therefore, if a read operation is attempted after reaching the end of the file, failbit is set, which explains why the "read until end of file" idiom works.

Upvotes: 2

Related Questions