The >> and << operators are evaluated left-to-right, so the following are equivalent statements, altho writing the parentheses would be rather weird.
cin >> a >> b >> c; (((cin >> a) >> b) >> c); // Same as above.What value is produced, for example, by
(cin >> a)
? And I mean what value is produced in the
expression, not what value is read into the variable.
It calls an overloaded templated function (operator>>
) in an
istream
class which reads input
and stores it into the variable on the right. It then returns the left operand
(ie, cin
) so the result can be used if there is another >> operator.
This chaining of the I/O operators is a rather clever solution.
Here's an example program that shows this.
if ((cin >> a) == cin) { cout << "Equal" << endl; // Yes, it is true } else { cout << "Not Equal" << endl; }
cin
can be used as a truth valueif (cin)which will be true if cin is ok and false if at an end-of-file or has encountered an error. It's type is
istream&
(input stream reference), so how can that be
used as a truth value.
The trick is that when it's evaluated in the context of a condition, eg, in an if
or while
statement, a special function is called in
the istream
class. This function returns a value that can
be interpreted as true or false.
Because the >> operator returns the iostream (eg, cin
), which can
be tested for EOF or errors, the cin loop
idiom can be used.
while (cin >> x) { . . . }which effectively tests for EOF, and also that the input is a valid value.