Introduction To C++ IO Streams

c++, casting, iostream, operator-overloading

Solution

`cin` is an instance of `istream` template class. `operator >>` acts on this istream instance to load input into data and returns a reference to this `istream`. Then in `while` condition it is tested by a call to `cin::operator void*() const` (`explicit operator bool() const` in C++11) which invokes `fail()` function to test if operation succeeded. This is why you can use this operation in while condition

while ( cin >> x)
{
   //...

Problem

I got a snippet of code from this article and I'm confused as to how it works? The snippet starts by saying: You can detect that a particular read or write operation failed by testing the result of the read. For example, to check that a valid integer is read from the user, you can do this: ``` int x; if ( cin >> x ) { cout << "Please enter a valid number" << endl; } ``` This works because the read operation returns a reference to the stream. I understand that the cin >> x operation returns a reference to cin but I'm still confused as to how evaluating the reference to the standard input stream object allows you to check that the input is a valid integer.

Original source