在下面的程序中:
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;
}
我使用了两种异常。程序在抛出“runtime_error”异常时运行良好,但在遇到“invalid_argument”异常时进入无限循环。实际上,catch block 中的“cin>>c
”语句存在问题,但无法弄清楚为什么会这样。
最佳答案
当 std::cin>>a>>b
遇到非数字字符时,会发生两件相关的事情:
- 违规字符未被消耗;
std::cin
的失败位已设置。
后者阻止所有对 std::cin
的进一步读取成功。这包括 invalid_argument
catch block 中的那些以及循环的后续迭代中的那些。
要解决此问题,您需要清除 std::cin
的状态并使用有问题的字符。这在 KennyTM 指出的以下答案中得到了很好的解释:C++ character to int .
关于c++ - c++ ("cin"语句中的 I/O 异常问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6624859/