我想捕获异常,当有人在cin上没有给出一个数值时,程序将读取下一个值。
#include <iostream>
using namespace std;
int main()
{
int x = 0;
while(true){
cin >> x;
cout << "x = " << x << endl;
}
return 0;
}发布于 2012-06-14 03:22:11
没有任何异常被抛出。相反,cin设置了一个“坏输入”标志。你想要的是:
while ((std::cout << "Enter input: ") && !(std::cin >> x)) {
std::cin.clear(); //clear the flag
std::cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); //discard the bad input
std::cout << "Invalid input; please re-enter.\n";
}This series of questions很好地解释了这一点。
链接:
clear()
ignore()
https://stackoverflow.com/questions/11021856
复制相似问题