What does cin >> x evaluate to, on error?

Viewed 99

Consider this snippet:

int a;
while (cin >> a){/* do something */}

On running this code, suppose I enter a string. The loop is exited. But then, since the expression inside while ends in error, and it doesn't evaluate to a bool type (is this incorrect thinking?), how does the compiler know to exit the loop?

5 Answers

cin >> x returns cin to allow chaining.

And in an boolean context, cin evaluates to true if and only if the last operation was successful.

Long story short, the loop will end on the first end of file or error.

cin >> a will always return a reference to cin.

The std::basic_ios base class has an explicit operator bool() that will be invoked when cin is "evaluated" in the condition of if, while, or for. When the operation fails, then failbit is set in the flags and the next time cin is converted to bool, the result is false because of the flag.

When you do

cin >> a

You call the basic_istream& operator>>( int& value ); and as you can see it returns basic_istream& so basically you have

while(cin)

and what that does is call

explicit operator bool() const;

which will return true if the stream is not in an error state and false if it is in an eror state. That is why the loop ends when there is an error.

The condition in while (cin >> a) is not when a != 0, but when std::cin is valid.

std::cin becomes invalid if you input string instead of int or if stream ends for example.

The class std::basic_ios, the base class of the class std::istream, has the conversion operator

explicit operator bool() const;

that returns true if the condition !fail().is true.

So if an error occurs in this statement

cin >> a

that returns the stream std::cin itself then it is contextually converted to the type bool with the value false and this loop

while (cin >> a){/* do something */}

does not execute its sub-statement.

Related