C++ Primer Section 1-2

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 input

  • cout—standard output

  • cerr—standard error—warnings and error messages

  • clog—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 ostream and istream, respectively.
  • The right-hand operand should be a value or object, to be written to the ostream or to be written by the value read from istream
  • The return value is an object of the type ostream or istream . 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值