while(cin) ! how does that works ?

here's a code that I saw and it works perfect but I don't know what does cin
doing in this code ?

while (cin && more) {
testOneNum();
cout << "More? [y = Yes, anything else No]: ";
cin >> c;
if (cin) more = (c == 'y');
}

------------------------------------------------
first, in while(cin && more) what does cin return here ?
second, in if(cin) what does cin return here ?
aren't we suppose to use cin with >> only ?
std::cin is an istream object.
istream objects have an evaluation operator, which means they can be evaluated as an expression. In the case of istream objects (and other streams), if it is evaluated as true, this means that no error flags have been set.
Error flags are set when any number of things go wrong, for instance:

1.) an input file stream object fails to open a file.

2.) you provide an input stream object with bad input.

3.) Lots of other things

if(cin)
means: if std::cin is valid (if none of std::cins error flags have been set)

1
2
int x;
if(cin >> x)

means: if std::cin can successfully read into x without setting an error flag
Last edited on
1
2
int x;
if(cin >> x)

In this context it is indicating whether or not the operation was successful, and thus whether the variable x contains a valid value which was supplied from the cin stream.

The code could be re-written like this:
1
2
3
int x;
cin >> x;            // attempt to read into x from the input stream
if ( !cin.fail() )   // test that the previous operation did not fail 

Here the fail() flag is explicitly tested.

http://www.cplusplus.com/reference/ios/ios/operator_bool/
Last edited on
Topic archived. No new replies allowed.