What values do the I/O operators (<< and >>) return?
C++ allows you to define functions to associate with existing operators. The << and >> operators, whose orginal meanings were bitwise left and right shift, have additional meanings for C++ iostreams. So how do they work?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; }
Why cin
can be used as a truth value
It's possible to make tests like
if (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.
Reading in the while condition
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.