我正在使用 C++ Primer 这本书学习 C++。
In 第1.4.3节,给出了以下关于读取未知数量的输入的示例代码。
#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;
}
根据这本书,如果我们输入3 4 5 6
,输出将是Sum is: 18
但是当我在我的电脑上尝试这个时(带有 MinGW 的 Windows 10),代码并没有结束。即使我输入换行符,它也会继续要求输入。仅当我输入非 int 输入时才有效f
.
这是预期的吗?如果是,是否有任何代码在输入换行符后停止?
我对 c++ 很陌生,而且我已经学过 python,所以这么早就陷入困境是相当令人沮丧的。
感谢致敬。
You need to terminate your input by an End-Of-File-character (i.e. CTRL-Z on Windows, CTRL-D on Mac/Unix), not just by an End-Of-Line (i.e. Enter).
A simple Enter is interpreted as white space, which will be simply ignored by operator>>
when reading into an integral data type.
CTRL-Z / End-Of-File, in contrast, makes any operator>>
fail with an error.
也可以看看这个答案 https://stackoverflow.com/a/16136924/2630032.
注意:输入f
也会终止你的循环,因为f
不被视为有效整数;因此,std::cin >> value
with value
存在类型int
和一个像这样的输入f
也会失败。更准确地说:operator>>
实际上返回对输入流的引用,但如果读入值失败,failbit
在流上设置,然后用布尔表达式解释流对象(隐式调用basic_istream::operator bool()
) 返回false
;所以也许这本书的作者不想在书中的相应部分解释这些细节:-)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)