首页 > 解决方案 > 按下输入键且没有用户输入时捕获异常

问题描述

我有这段代码要求用户输入并期望一个int。但有时,用户可能会忘记输入或输入错误并按下回车键而不输入任何内容,导致我的程序因以下错误而终止:

terminate called after throwing an instance of 'std::invalid_argument'

  what():  stoi

我有一个函数可以检查我的输入是否为 int 并在异常发生时捕获该异常,同时忽略该输入。我正在寻找一种类似的方法来捕获这个无输入错误:捕获异常并忽略它,而不是终止我的程序。

这是我的代码:

        int choice;
        string theInput;

        getline(cin, theInput);
        while(cin.fail() || cin.eof() || theInput.find_first_not_of("0123456789") != string::npos) { 
// checks if input is a number
            cout << "Error: input not a number" << endl;
            if( theInput.find_first_not_of("0123456789") == string::npos) {
                cin.clear();
                cin.ignore(256,'\n');
            }
            system("CLS");
        }

        string::size_type st;
        choice = stoi(theInput,&st);

感谢:D

标签: c++exception

解决方案


推荐阅读