To read input from a stream, we use the >> operator:
int i; char b[30]; cin >> i; // Reads an int from standard input cin >> b; // Reads a "word" from standard input Any amount of leading whitespace will be skipped. Reading into a char array is interpreted as "read word". A "word" is a sequence of non-whitespace characters.
About the >> operator
>> is a binary operator, just like addition (+). It has the following odd properties, which do not seem so odd when you consider that other operators are just as odd:
Like most other binary operators, the meaning of >> differs based on the types of its arguments (this may not be obvious in the case of addition, but consider the different meanings of
"1 + 1" and"1.0 + 1.0" ). In the example above, the >> operator will invoke a different input routine based on the type of the arguments.We therefore say the operator is overloaded---the same name can mean different things.
Also like any other binary operator, >> takes two operands and returns a value. When the operator >> is used with an istream as the left argument, the return value is of type istream &---that is, a "reference to an istream object".
Furthermore, the >> operator is left-associative. This means that, all else being equal, we evaluate expressions from left to right. In the following expression:
cin >> b >> i >> n; we first evaluate "cin >> b", which returns a reference to an istream object (which will be cin). We then evaluate the result of using this istream object with ">> i", which results in the output of i, and so on.
Also, note that the precedence of the >> and << operators is lower than that of most arithmetic operations. Therefore, in the following line:
cout << i+2; we evaluate the "i+2" expression before applying the << operation. However, there are operators whose precedence is lower than <<. One example is | (bitwise or).