c++ 中 I/O 异常问题(“cin”声明)
在下面的程序中:
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 块中的“cin>>c
”语句存在问题,但无法弄清楚为什么会发生这种情况。
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. Actually there is problem in "cin>>c
" statement in catch-block but can not figure out, why this is happening.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当 std::cin>>a>>b 遇到非数字字符时,会发生两个相关的事情:
std::cin
的失败位已设置。后者会阻止从
std::cin
进行的所有进一步读取成功。这包括invalid_argument
catch 块内的内容以及循环后续迭代内的内容。要解决此问题,您需要清除
std::cin
的状态并使用有问题的字符。 KennyTM 指出的以下答案很好地解释了这一点: C++ 字符到 int。When
std::cin>>a>>b
encounters a non-numeric character, two relevant things happen:std::cin
is set.The latter prevents all further reads from
std::cin
from succeeding. This includes those inside yourinvalid_argument
catch block and those inside subsequent iterations of the loop.To fix this, you need to clear the state of
std::cin
and to consume the offending character. This is explained very well in the following answer pointed out by KennyTM: C++ character to int.您可以使用 异常掩码,您可能会找到更好的方法来处理错误。
You can play with exception masks, you might find a preferable way to handle errors.