这是我在一本书中找到的代码片段:
#include <iostream>
int main()
{
// currVal is the number we're counting; we'll read new values into val
int currVal = 0, val = 0;
// read first number and ensure that we have data to process
if (std::cin >> currVal) {
int cnt = 1; // store the count for the current value we're processing
while (std::cin >> val) { // read the remaining numbers
if (val == currVal) // if the values are the same
++cnt; // add 1 to cnt
else { // otherwise, print the count for the previous value
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
currVal = val; // remember the new value
cnt = 1; // reset the counter
}
} // while loop ends here
// remember to print the count for the last value in the file
std::cout << currVal << " occurs "
<< cnt << " times" << std::endl;
} // outermost if statement ends here
return 0;
}
此代码片段计算一个数字在输入流中输入了多少次,并使用 while 循环接收未知数量的数字。
然而,问题是当我输入不同的数字而不是一个重复的数字时。 (并输入 Ctrl+D,表示文件结束)。输入流似乎需要额外的输入才能显示最后一个值出现的次数。
例如如果我输入
1 2 3 4
以空格分隔,最后按 Ctrl+D 表示文件结束,输出将是:
1 occurs 1 times
2 occurs 1 times
3 occurs 1 times
<requests for input>
4 occurs 1 times
但是如果我在流中输入不是整数的东西
1 2 3 4a
如预期的那样,输出运行顺利。
这是为什么?
最佳答案
while (std::cin >> val)
将循环直到 cin
进入不再有效的状态。使用 Ctrl+D 发送 EOF 字符,这会导致 cin
的 eof
标志被设置并导致它评估为 false
结束循环。
1 2 3 4a
的输入基本上做同样的事情。当您在 cin
需要一个数字时输入一个字母时,它会导致输入失败,从而设置 cin
的 fail
标志。这也会导致 cin
评估为 false
并结束循环。
解决所有这些问题的一种方法是使用 std::string
并一次获取所有输入。然后您可以将该 std::string
加载到 std::stringstream
中并从中获取各个元素。
std::string line;
std::getline(cin, line)
std::stringstream ss(line);
while (ss >> val)
{
//...
}
关于c++ - 此代码片段中的 while 循环如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51309441/