if (cin >> x) – Why can you use that condition?

cin is an object of class istream that represents the standard input stream. It corresponds to the cstdio stream stdin. The operator >>overload for streams return a reference to the same stream. The stream itself can be evaluated in a boolean condition to true or false through a conversion operator.

cin provides formatted stream extraction. The operation
cin >> x;

where “x” is an int will fail if a non-numeric value is
entered. So:

if(cin>>x)

will return false if you enter a letter rather than a digit.

This website on tips and tricks using C++ I/O will help you too.

Leave a Comment