我在做一些练习来打发时间,遇到了一个我不理解的行为,我来解释一下:
练习:
Write a program that reads and stores a series of integers and then computes the sum of the first
N
integers. First, ask forN
, then read the values into a vector, then calculate the sum of the firstN
values.
因为我要求 N
作为第二步:
在第二个 std::cin
(std::cin >> values_to_compute
) 中,它必须离开 while 语句才能继续程序,“只有当”读到的不是双重的。例如,我可以打字; 'k' 或“你好吗?”或 Ctrl + Z(我在 Windows 10 上)。
int main() {
try {
double holder {0};
std::vector<double> values;
while (std::cin >> holder) {
values.push_back(holder);
}
std::cin.clear();
std::cout << "Out of the loop, now entering to the other std::cin\n";
int values_to_compute {0};
std::cin >> values_to_compute;
std::cout << "Computing...\n";
double result_computed {0};
for (int i {0}; i < values_to_compute; ++i) {
result_computed += values[i];
}
std::cout << "Result computed " << result_computed << '\n';
system("pause");
return 0;
}
catch (std::runtime_error& e) {
std::cerr << e.what() << '\n';
system("pause");
return 1;
}
}
好吗?
所以... std::cin
使 while 处于 not good() 状态。我必须调用 std::cin.clear()
才能再次使用 std::cin
。
好的,然后呢?
好吧,如果我键入 Ctrl+Z 退出 while
循环,std::cin.clear()
作品;如果我键入的内容不是 Ctrl + Z,则 std::cin.clear()
不起作用。
我想知道这种行为的原因。
最佳答案
那是因为std::cin::clear
清除 cin
的错误状态但它不会从流中删除数据。您可以使用 std::cin::ignore()
在阅读之前阅读并丢弃一行文本 values_to_compute
.
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
确保#include <limits>
得到std::numeric_limits
.
关于c++ - 为什么 std::cin.clear() 在这个简单的程序中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54640425/