注意:这篇文章上次更新于1975天前,文章内容可能已经过时。
This article was last updated1975 days ago, the content may be outdated.
1 |
|
解释
表达式std::cin >> value 是从标准输入中读取下一个数,保存在 value 中。输入运算符>> 返回其左侧运算对象,在本例中是 std::cin,因此,此循环条件实际上就是检测std::cin。
当我们使用一个 istream 对象作为条件时,其效果就是检测流的状态。如果流是有效的,即流未遇到错误,那么检测成功。当遇到文件结束符,或者遇到一个无效的输入时,istream 对象的状态就会变为无效。处于无效状态的 istream 对象会使条件为假。
因此,我们的 while 循环会一直执行直到遇到文件结束符(或输入错误)。
那么,什么是文件结束符,如何从键盘输入文件结束符?
对于不同的操作系统而言,有着不同的约定。在 Windows 系统中,输入文件结束符的方法是 Ctrl + Z,然后按 Enter 键。在 Unix 系统中,包括 Mac OS X 系统中,文件结束符的输入是用 Ctrl + D。

Explanation
The expression std::cin >> value reads the next number from the standard input and stores it in value. The input operator >> returns its left-hand operand, which in this case is std::cin. Therefore, this loop condition is essentially testing std::cin.
When we use an istream object as a condition, the effect is to check the state of the stream. If the stream is valid — that is, it has not encountered an error — the check succeeds. When it encounters an end-of-file or an invalid input, the state of the istream object becomes invalid. An istream object in an invalid state makes the condition false.
Therefore, our while loop keeps executing until it encounters an end-of-file (or an input error).
So, what is an end-of-file, and how do you type an end-of-file from the keyboard?
Different operating systems have different conventions. On Windows, you enter an end-of-file by pressing Ctrl + Z and then pressing Enter. On Unix systems, including Mac OS X, you enter an end-of-file with Ctrl + D.



