[英]problem with I/O exception in c++ (“cin” statement)
In the following program:在以下程序中:
int main(){
std::cout<<"enter numbers to be divide"<<std::endl;
int a,b,c;
while(true){
try{
if(!(std::cin>>a>>b)){
throw std::invalid_argument("please enter proper interger");
}
if(b==0){
throw std::runtime_error("please enter enter nonzero divisor");
}
c=a/b;
std::cout<<"quotient = "<<c<<std::endl;
}
catch(std::invalid_argument e){
std::cout<<e.what()<<"\ntry again?enter y/n";
char c;
std::cin>>c;
if(c=='n'||c=='N') break;
}
catch(std::runtime_error e){
std::cout<<e.what()<<"\ntry again?enter y/n";
char c;
std::cin>>c;
if(c=='n'||c=='N') break;
}
}
return 0;
}
I am using two kinds of exception.Program is working perfectly when it throws "runtime_error" exception but goes into infinite loop when encounter "invalid_argument" exception.我正在使用两种异常。程序在抛出“runtime_error”异常时运行良好,但在遇到“invalid_argument”异常时进入无限循环。 Actually there is problem in "
cin>>c
" statement in catch-block but can not figure out, why this is happening.实际上,catch-block 中的“
cin>>c
”语句存在问题,但无法弄清楚为什么会这样。
When std::cin>>a>>b
encounters a non-numeric character, two relevant things happen:当
std::cin>>a>>b
遇到非数字字符时,会发生两件相关的事情:
std::cin
is set.std::cin
的失败位。 The latter prevents all further reads from std::cin
from succeeding.后者会阻止来自
std::cin
的所有进一步读取成功。 This includes those inside your invalid_argument
catch block and those inside subsequent iterations of the loop.这包括您的
invalid_argument
catch 块中的那些以及循环的后续迭代中的那些。
To fix this, you need to clear the state of std::cin
and to consume the offending character.要解决此问题,您需要清除
std::cin
的 state 并消耗违规字符。 This is explained very well in the following answer pointed out by KennyTM: C++ character to int . KennyTM 指出的以下答案很好地解释了这一点: C++ character to int 。
You can play with exception masks , you might find a preferable way to handle errors.您可以使用异常掩码,您可能会找到一种更好的方法来处理错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.