std::cin 不会在错误的输入上引发异常

std::cin doesn't throw an exception on bad input

本文关键字:输入 异常 错误 cin std      更新时间:2023-10-16

我只是想写一个简单的程序,从cin中读取,然后验证输入是否为整数。如果真的发生了,我将打破我的while循环。如果没有,我将再次请求用户输入。

我的程序编译和运行都很好,这太棒了。但是,如果我输入一个非数字值,它不会提示新的输入。什么东西?

#include <iostream>
using namespace std;
int main() {
    bool flag = true;
    int input;
    while(flag){
        try{ 
            cout << "Please enter an integral value n";
            cin >> input;
            if (!( input % 1 ) || input == 0){ break; }
        }
        catch (exception& e)
        { cout << "Please enter an integral value"; 
        flag = true;}
    }
    cout << input;
    return 0;
}

C++iostream不使用异常,除非您告诉他们使用cin.exceptions( /* conditions for exception */ )

但是,您的代码流更自然,无一例外。只需执行if (!(cin >> input))

再次尝试之前,还记得清除失败位。

整个事情可以是:

int main()
{
    int input;
    do {
       cout << "Please enter an integral value n";
       cin.clear();
       cin.ignore(std::numeric_limits<std::streamsize>::max(), 'n');
    } while(!(cin >> input));
    cout << input;
    return 0;
}

不要使用using namespace std;,而是导入您需要的内容。

最好一次输入一行。如果您在一行中有多个单词,或者在键入任何内容之前按enter键,这将使行为更加直观。

#include <iostream>
#include <sstream>
#include <string>
using std::cerr;
using std::cin;
using std::cout;
using std::endl;
using std::flush;
using std::getline;
using std::istringstream;
using std::string;
int main() {
    int input;
    while (true)
    {
        cout << "Please enter an integral value: " << flush;
        string line;
        if (!getline(cin, line)) {
            cerr << "input failed" << endl;
            return 1;
        }
        istringstream line_stream(line);
        char extra;
        if (line_stream >> input && !(line_stream >> extra))
            break;
    }
    cout << input << endl;
    return 0;
}