Reading from a Stream
Having asked the user for input, we next want to read that input. We start by defining two variables named v1 and v2 to hold the input:
- int v1 = 0, v2 = 0;
We define these variables as type int, which is a built-in type representing integers. We also initialize them to 0. When we initialize a variable, we give it the indicated value at the same time as the variable is created.
The next statement
- std::cin >> v1 >> v2;
reads the input. The input operator (the . operator) behaves analogously to the output operator. It takes an istream as its left-hand operand and an object as its right-hand operand. It reads data from the given istream and stores what was read in the given object. Like the output operator, the input operator returns its left-hand operand as its result. Hence, this expression is equivalent to
- (std::cin >> v1) >> v2;
Because the operator returns its left-hand operand, we can combine a sequence of input requests into a single statement. Our input operation reads two values from std::cin, storing the first in v1 and the second in v2. In other words, our input operation executes as
- std::cin >> v1;
- std::cin >> v2;
Completing the Program
What remains is to print our result:
- std::cout << "The sum of " << v1 << " and " << v2
- << " is " << v1 + v2 << std::endl;
This statement, although longer than the one that prompted the user for input, is conceptually similar. It prints each of its operands on the standard output. What is interesting in this example is that the operands are not all the same kinds of values. Some operands are string literals, such as "The sum of ". Others are int values, such as v1, v2, and the result of eva luating the arithmetic expression v1 + v2. The library defines versions of the input and output operators that handle operands of each of these differing types.