Section 1-2
Contents and Thoughts
Objects for I/O Stream
In the header iostream , four objects for I/O stream are defined.
cin— standard inputcout—standard outputcerr—standard error—warnings and error messagesclog—general information about execution of the program
Operators and Operands for I/O stream
<< and >> operators are almost the same.
- The left-hand operands should be an object of
ostreamandistream, respectively. - The right-hand operand should be a value or object, to be written to the
ostreamor to be written by the value read fromistream - The return value is an object of the type
ostreamoristream. And that is why these two statements are equivalent.
std::cin >> v1 >> v2;
(std::cin >> v1) >> v2;
and vice versa.
Exercise
Exercise 1-3
Write a program to print Hello, World on the standard output.
Solution
In 1-3.cpp
Exercise 1-4
Our program(../Example Code/AddTwoNumbers.cpp) used the addition operator, + , to add two numbers. Write a program that uses the multiplication operator *, to print the product instead.
Solution
In 1-4.cpp
Exercise 1-5
We wrote the output in one large statement. Rewrite the program to use a separate statement to print each operand.
Solution
In 1-5.cpp
Exercise 1-6
Explain whether the following program fragment is legal.
std::cout << "The sum of" << v1;
<< " and " << v2;
<< " is " << v1 + v2 << std::endl;
If the program is legal, what does it do? If the program is not legal, why not? How would you fix it?
Solution
This program fragment is not legal. The operator<< needs two operands. But the operators in line 2 and 3 do not have the left-hand operants which should be an object in ostream.
How to fix it?
Erase all the semicolons except that one in the last line.

被折叠的 条评论
为什么被折叠?



