C++简单的捕获捕获循环解决方案
我不明白这为什么会失败。为什么在抛出错误后它会一直循环C++简单的捕获捕获循环解决方案,c++,try-catch,gnu,C++,Try Catch,Gnu,我不明白这为什么会失败。为什么在抛出错误后它会一直循环 bool undone; do { undone = false; try { o.spr(); // function throwing error E object } catch(E &r) { undone = true; cout << r.reason << endl; } } while(u
bool undone;
do
{
undone = false;
try
{
o.spr(); // function throwing error E object
}
catch(E &r)
{
undone = true;
cout << r.reason << endl;
}
}
while(undone);
以下是函数:
void spr()
{
E r;
int n;
cout << " put n : "<<endl;
cin >> n;
if (cin.fail())
{
r.reason="fail !!";
throw r;
}
cout << " your n is : "<< n;
}
如果o.spr抛出,则将“撤消”设置为true。然后while中的条件被检查,它是真的,所以它循环,再次尝试调用o.spr,等等。。。重新考虑undone标志及其值。错误发生后,问题正在恢复 首先,您必须使用cin.clear清除cin中的错误标志。然后,您必须读取错误输入,以便下次不会导致错误:
void spr()
{
E r;
int n;
cout << " put n : "<<endl;
cin >> n;
if (cin.fail())
{
cin.clear(); // clear the error flag
std::string bad_input;
cin >> bad_input; // skip over bad input
// now it is safe to re-use cin
r.reason="fail !!";
throw r;
}
cout << " your n is : "<< n;
}
可能是跳过错误输入的更好方法:
void spr()
{
E r;
int n;
cout << " put n : "<<endl;
cin >> n;
if (cin.fail())
{
cin.clear(); // clear the error flag
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip over bad input
r.reason="fail !!";
throw r;
}
cout << " your n is : "<< n;
}
cin.ignore函数跳过最大可能的输入字符数,直到到达行'\n'字符的末尾。可能每次调用o.spr时都会抛出它。不,对于好的输入,它工作得很好。然后你就有了坏的输入。我想在它失败后,你需要使用cin.clear。但是再次出现undone=false;在循环开始时。它不会改变一切吗?只有o.spr没有抛出错误,它才会保持为false。不过,它似乎每次都会扔。不是吗?void spr{E r;int n;可以再问我一次n吗?哦,很明显。Galik的anwers是正确的。我完全错过了,应该先问你的意见。谢谢!很好!