cin的异常如何恢复?(在线等)
以下程序是想测试:当输入流要求int型数据,而输入字符型数据时如何通过异常检验错误并恢复。现在的问题是,我已经能捕获异常,但无法将cin恢复到正常状态。程序执行结果在代码后。
那个高手指点一下。
#include <iostream>
using namespace std;
int getint()
{
int i;
cin >> i;
cout << "i=" << i << endl;
return i;
}
int main()
{
int j;
cin.exceptions(ios_base::failbit);
for( int i = 0; i < 3; ++i )
{
try
{
j = getint();
break;
}
catch(ios_base::failure& exe)
{
cout << "catch exception\n";
cin.clear(ios_base::goodbit);
}
}
cout << j;
}
/*
input:
a
output:
catch exception
catch exception
catch exception
4194304
*/