不管用goto还是while都是无限循环,求问这是为什么
代码如下:
#include <iostream>
#include <stdexcept>
#include <exception>
using namespace::std;
int main(){
int a, result{ 1 };
cout << "input a number:" << endl;
// retry:
// try{
// cin >> a;
// if (cin.fail())
// throw runtime_error("not a number!");
// }catch(runtime_error e){
// cout << e.what() << endl;
// goto retry;
// }
while(!(cin >> a)){
cout << "not a number!" << endl;
}
do{
result *= a;
}while(a-- > 1);
cout << "result is:\n\t" << result << endl;
return 0;
}
首先:出错后,cin.fail()
这种状态一旦标记上后就一直为真,需要用 cin.clear();
清除状态。
其次:出错后,原先导致错误的字符还在输入缓冲区,你继续用一样的方法读取还是一样的错误。应该用 cin.ignore();
丢弃一个字符。
加上上面这两句代码。
int a = -1;
while(1)
{
cin >> a;
if (a != -1)
{
break;
}
cin.clear();
cin.ignore();
}