while(cout << "How many elements do you want: " && !(cin >> el))
{
cin.sync();
cin.clear();
cout << " Invalid input!\n";
}
el 是一个 int,当我输入一个字符时,循环就会无限循环。 我按照 SO 中的一篇文章修复了错误的输入,但它不起作用,它无限循环打印“您想要多少个元素:无效输入!” 我也尝试过忽略(10000,“\n”),但仍然不起作用......
最佳答案
当从流读取时发生错误时,会设置一个错误标志,并且在清除错误标志之前无法再进行读取。
That's why you get an infinite loop.
改为使用:
cin.clear(); // clears the error flags
// this line discards all the input waiting in the stream
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
关于c++ - cin.sync 和clear 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21810112/