【问题标题】:How should I make my program correctly handle all user inputs?我应该如何让我的程序正确处理所有用户输入?
【发布时间】:2017-09-02 23:39:54
【问题描述】:

我想创建一个可以正确处理所有输入的输入系统。所需的用户输入是双重的。当用户输入字符串时,字符串流失败并处理异常。但是,该程序无法处理诸如“3245 2345 5”和“21523i4jf”之类的输入,而不是将它们标记为不正确的输入,而是在字符串的开头注册数字并将其传递给 double number 而不会引发异常。

while (true)
{
    string user_input;
    cout << "Your Choice: ";
    getline (cin, user_input);
    cout << endl;

    if (user_input == "quit")
    {
        break;
    }

    try
    {
        double number;
        stringstream stringstream_input;

        stringstream_input << user_input;
        stringstream_input >> number;

        if (stringstream_input.fail())
        {
            throw 90;
        }

        cout << number << endl << endl;
    }

    catch (int x)
    {
        cout << "Please enter a valid input!" << endl << endl;
    }
}

【问题讨论】:

标签: c++ exception-handling user-input sstream


【解决方案1】:

您可以使用std::stod() 来正确处理。

try {
    number = std::stod(user_input);
}
catch(const std::invalid_argument& e) {
    std::cerr << "Invalid input '" << user_input << "'" << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-24
    • 1970-01-01
    • 2011-02-24
    • 1970-01-01
    • 2011-06-28
    • 1970-01-01
    • 2022-01-16
    • 1970-01-01
    相关资源
    最近更新 更多