为什么下面的代码在输入字符或字符串时会出现死循环?我已经看到有关它的问题,以及答案中提供的解决方案(例如 here ),但它似乎根本没有帮助。该代码实现了那里建议的解决方案,但它仍然会导致无限循环。
#include <iostream>
#include <bitset>
#include <limits>
using namespace std;
int main() {
int n;
while (!(cin >> n)) {
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cin.clear();
cout << std::bitset<8>(cin.rdstate()) << endl;
cin >> n;
cout << std::bitset<8>(cin.rdstate()) << endl;
}
cout << n;
return 0;
}
g++ --version
产生以下内容:g++ (Ubuntu 6.2.0-5ubuntu12) 6.2.0 20161005
程序的输出如下:
00000000
00000100
00000000
00000100
... and so on
尽管流已被清除并且所有输入已被忽略,但似乎正在重新输入该值。
最佳答案
您在 clear
之前调用了 ignore
,但是 ignore
仅在流没有错误的情况下才起作用,但它总是在那个点上有错误。< br/>
当你切换这两个语句时它工作正常:在一个或几个无效输入之后,你需要 2 个连续的有效输入才能成功终止程序。
关于c++ - std::cin 导致无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43023413/