输入未知数目数据,计算总和:
#include <iostream>
int main()
{
int sum = 0, value;
while (std::cin >> value)
sum += value;
std::cout << "Sum is "
<< sum << std::endl;
return 0;
}
std::cin >> value返回std::cin,while测试 std::cin就是测试std::cin的状态,流有两种状态,有效和无效,
有效的表示读入下一个数是可能的,这时测试成功,即循环可以继续进行。
无效的表示遇到文件描述符EOF或遇到了无效输入,比如给一个整型变量赋值了一个不是整数的值(比如+),则流对象变成无效的,导致条件失败。循环结束。
文件结束符:
windows 下 键入ctrl+z
linux 下键入 ctrl+d
如果想实现按回车结束:
可以这样:
while (std::cin.peek() != '\n' && std::cin >> value)
The function peek() is used with input streams, and returns the next character in the stream or EOF if the end of file is read. peek() does not remove the character from the stream.
函数peek() 用于输入流中,它返回流中下一个值,如果读到文件的结尾,它返回文件结束符。peek()函数不会将流中的字符删去。