如何在C++捕获此异常

How to catch this exception C++

本文关键字:异常 C++      更新时间:2023-10-16

我想捕获异常,当有人在 cin 上没有给出数字值时会发生,因此程序将读取下一个值。

#include <iostream>
using namespace std;
int main()
{
    int x = 0;
    while(true){
        cin >> x;
        cout << "x = " << x << endl;
    }
    return 0;
}

如果你真的想使用异常处理,你可以做这样的事情:

cin.exceptions(ios_base::failbit); // throw on rejected input
try {
// some code
int choice;
cin >> choice;
// some more code
} catch(const ios_base::failure& e) {
    cout << "What was that?n";
    break;
} 

参考: http://www.cplusplus.com/forum/beginner/71540/

根本没有抛出异常。相反,cin设置了某种"错误输入"标志。你想要的是这个:

while ((std::cout << "Enter input: ") && !(std::cin >> x)) {
    std::cin.clear(); //clear the flag
    std::cin.ignore (std::numeric_limits<std::streamsize>::max(), 'n'); //discard the bad input
    std::cout << "Invalid input; please re-enter.n";
}

这一系列的问题很好地解释了它。

链接:

clear() ignore()

添加类似以下内容:

if(cin.fail())
{   
  cin.clear();
  cin.ignore(std::numeric_limits<std::streamsize>::max(),' '); 
  cout << "Please enter valid input";
} 
int main()
{
    int x = 0;
    cin.exceptions(ios::failbit);
    while(true){
        try
        {
            cin>>x;
        }
        catch(ios_base::failure& e)
        {
            //..
        }
        cout<<"x = "<<x<<endl;
    }
    return 0;
}

这应该有效。