我想捕获异常,当有人在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:23:06
如果你真的想使用异常处理,你可以这样做:
cin.exceptions(ios_base::failbit); // throw on rejected input
try {
// some code
int choice;
cin >> choice;
// some more code
} catch(const ios_base::failure& e) {
cout << "What was that?\n";
break;
} 参考:http://www.cplusplus.com/forum/beginner/71540/
发布于 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()
发布于 2012-06-14 03:26:16
添加如下内容:
if(cin.fail())
{
cin.clear();
cin.ignore(std::numeric_limits<std::streamsize>::max(),' ');
cout << "Please enter valid input";
} https://stackoverflow.com/questions/11021856
复制相似问题