如何避免使用Try-Catch(C++)在整数值中输入字符串

How to avoid Input a String in an Integer value using Try Catch (C++)

本文关键字:整数 字符串 输入 C++ 何避免 Try-Catch      更新时间:2023-10-16

我只是希望用户避免使用Try Catch在整数值中输入字符串,因为使用while循环根本不起作用。我知道如何在Java中使用TryCatch,但在C++中我不知道。我一直在尝试这样的东西:

#include <iostream>
using namespace std;
main(){
   int opc;
   bool aux=true;
   do{
   try{
       cout<<"PLEASE INSERT VALUE:"<<endl;
       cin>>opc;
       aux=true;
   }
   catch(int e){
             aux=false;
             throw e;
             cout<<"PLEASE INSERT A VALID OPTION."<<endl;
           }
           }while(aux==false);
       system("PAUSE");
         }//main

更简单、更好的方法可以做到这一点,但如果您真的想要异常,可以启用它们并捕获std::ios_base::failure。类似这样的东西:

int main() {
    int opc;
    bool aux = true;
    cin.exceptions(std::istream::failbit);
    do {
        try {
            cout << "PLEASE INSERT VALUE:" << endl;
            cin >> opc;
            aux = true;
        }
        catch (std::ios_base::failure &fail) {
            aux = false;
            cout << "PLEASE INSERT A VALID OPTION." << endl;
            cin.clear();
            std::string tmp;
            getline(cin, tmp);
        }
    } while (aux == false);
    system("PAUSE");
}

在正常情况下,当提供的数据不合适时,std::cin作为所有istream不会抛出异常。流将其内部状态更改为false。所以你可以简单地做一些事情:

int n;
std::cin >>n;
if(!std::cin) {
 // last read failed either due to I/O error
 // EOF. Or the last stream of chars wasn't
 // a valid number
 std::cout << "This wasn't a number" << std::endl;
}
int opc;
cin >> opc;

当您尝试读取非数字值时,将设置流的坏位。您可以检查流是否处于良好状态。如果没有,请重置状态标志,如果需要,请重试读取。请注意,当设置坏位时,将忽略后面的任何读取。因此,在进行另一次尝试之前,您应该先清除输入流中的坏比特,然后忽略其余的坏输入。

// If the input stream is in good state
if (cin >> opc)
{
   cout << opc << endl;
}
else
{
   // Clear the bad state
   cin.clear();
   // Ignore the rest of the line
   cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
// Now if the user enters an integer, it'll be read
cin >> opc;
cout << opc << endl;