嗯,是的。您的 try-catch 语句在循环内。所以你尝试一些东西,它失败并抛出一个异常,然后你捕捉到异常,你永远不会退出或从循环中返回,所以你再次做同样的事情。
但是由于您的输入第一次没有被处理(而是抛出异常),所以第二次、第三次或任何时候都不会处理它。
要前进,通过忽略输入直到下一个空格来处理异常:
int input;
while (1 == 1){
cout << "Enter a number: ";
try{
cin.exceptions(istream::failbit);
cin >> input;
}catch(ios::failure){
cout << "Not a number\n";
input = 0;
//the line below ignores all characters in cin until the space (' ')
//(up to 256 characters are ignored, make this number as large as necessary
cin.ignore(256, ' ');
}
}
顺便说一句,作为一般规则:异常应该是真正异常的东西,特别是因为处理异常存在开销。关于无效的用户输入是否异常存在争论。
作为替代方案,您可以创建一个更紧凑、同样正确的循环,而不会出现以下异常:
int input;
while (true){ //outer while loop that repeats forever. Same as "while(1 == 1)"
cout << "Enter a number: ";
//The following loop just keeps repeating until a valid value is entered.
//The condition (cin >> input) is false if e.g. the value is a character,
//or it is too long to fit inside an int.
while(!(cin >> input)) {
cout << "Not a number" << endl;
input = 0;
}
}