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

Viewed 63989

I have been using "Accelerated C++" to learn C++ over the summer, and there's a concept which I don't seem to understand properly.

Why is

int x;
if (cin >> x){}

equivalent to

cin >> x;
if (cin){}

By looking at the code, it seems to me that we're using cin as a variable. But, I thought it was a function. Why can we use cin in this way when it is x that has whatever value we input into our keyboard?

9 Answers

std::cin is an instance of the std::istream class.

cin >> x is just calling a function on the cin object. You can call the function directly:

cin.operator >>(x);

To allow you to read multiple variables at once the operator >> function returns a reference to the stream it was called on. You can call:

cin >> x >> y;

or equivalently:

cin.operator >>(x).operator >>(y);

or:

std::istream& stream = cin.operator >>(x);
stream.operator >>(y);

The final part of the puzzle is that std::istream is convertible to bool. The bool is equivalent to calling !fail().

So in the following code:

int x;
std::istream& stream = std::cin.operator >>(x);
bool readOK = !stream.fail();
if (readOK)
{
  std::cout << x << "\n";
}

bool readOK = !stream.fail(); can be reduced to just bool readOK = stream;.

You don't need a separate bool to store the stream state so can just do if (stream).

Removing the temporary stream variable gives if (std::cin.operator >>(x)).

Using the operator directly gets us back to the original code:

int x;
if (std::cin >> x)
{
  std::cout << x << "\n";
}
Related