c++ primer 第一章 标准输入输出——cin cout

c++ primer 第一章 标准输入输出——cin cout

参考书:

c++ primer (5th)

1. << 运算符

std::cout << "Enter two numbers:" << std::endl;

The << operator takes two operands: The left-hand operand must be an ostream object; the right-hand operand is a value to print.

The operator writes the given value on the given ostream.

The result of the output operator is its left-hand operand.
That is, the result is the ostream on which we wrote the given value.

Our output statement uses the << operator twice. Because the operator returns its left-hand operand, the result of the first operator becomes the left-hand operand of the second.

As a result, we can chain together output requests.

Thus, our expression is equivalent to

(std::cout << "Enter two numbers:") << std::endl;

Each operator in the chain has the same object as its left-hand operand, in this case std::cout.

Alternatively, we can generate the same output using two statements:

std::cout << "Enter two numbers:";
std::cout << std::endl;

The first output operator prints a message to the user. That message is a string literal, which is a sequence of characters enclosed in double quotation marks.

The second operator prints endl, which is a special value called a manipulator. Writing endl has the effect of ending the current line and flushing the buffer associated with that device.

Flushing the buffer ensures that all the output the program has generated so far is actually written to the output stream, rather than sitting in memory waiting to be written.

2. Reading an Unknown Number of Inputs

#include <iostream>
int main()
{
int sum = 0, value = 0;
// read until end-of-file, calculating a running total of all values read
while (std::cin >> value)
sum += value; // equivalent to sum = sum + value
std::cout << "Sum is: " << sum << std::endl;
return 0;
}
while (std::cin >> value)

Evaluating the while condition executes the expression
std::cin >> value .

When we use an istream as a condition, the effect is to test the state of the stream.

If the stream is valid—that is, if the stream hasn’t encountered an error—then the test succeeds.

An istream becomes invalid when we hit end-of-file or encounter an invalid input, such as reading a value that is not an integer.

An istream that is in an invalid state will cause the condition to yield false.

发布了120 篇原创文章 · 获赞 2 · 访问量 5784

猜你喜欢

转载自blog.csdn.net/Lee567/article/details/104080145