If (Cin ≫≫ X) - Why Can You Use That Condition

How does cin evaluate to true when inside an if statement?

The answer depends on the version of the standard C++ library:

  • Prior to C++11 the conversion inside if relied on converting the stream to void* using operator void*
  • Starting with C++11 the conversion relies on operator bool of std::istream

Note that std::cin >> X is not only a statement, but also an expression. It returns std::cin. This behavior is required for "chained" input, e.g. std::cin >> X >> Y >> Z. The same behavior comes in handy when you place input inside an if: the resultant stream gets passed to operator bool or operator void*, so a boolean value gets fed to the conditional.

What is the difference between if (cin >> x) and if (!(cin >> x).fail())?

Here the expression cin >> x performs an input operation that might update x, and as its expression result returns a reference to the stream, i.e. to cin. So cin is being used directly as a condition. That invokes a conversion to boolean, which is defined such that it on its own is equivalent to !cin.fail() (i.e., the expression cin >> x as condition is equivalent to writing !(cin >> x).fail() or, as a comma expression, (cin >> x, !cin.fail()).

about while (!(cin>>x))

You use

cin >> number;

And then

   while (!(cin>>x)) 

Both of which read a number.



Related Topics



Leave a reply



Submit