【问题标题】:User input of integer followed by garbage用户输入整数,后跟垃圾
【发布时间】:2014-02-08 17:47:14
【问题描述】:

在我的简单Fraction 类中,我有以下方法来获取numerator 的用户输入,该方法适用于检查garbage 之类的垃圾输入,但无法识别以整数开头的用户输入,然后是垃圾,1 garbage1garbage

void Fraction::inputNumerator()
{
    int inputNumerator;

    // loop forever until the code hits a BREAK
    while (true) {
        std::cout << "Enter the numerator: ";

        // attempt to get the int value from standard input
        std::cin >> inputNumerator;

        // check to see if the input stream read the input as a number
        if (std::cin.good()) {

            numerator = inputNumerator;
            break;

        } else {

            // the input couldn't successfully be turned into a number, so the
            // characters that were in the buffer that couldn't convert are
            // still sitting there unprocessed.  We can read them as a string
            // and look for the "quit"

            // clear the error status of the standard input so we can read
            std::cin.clear();

            std::string str;
            std::cin >> str;

            // Break out of the loop if we see the string 'quit'
            if (str == "quit") {
                std::cout << "Goodbye!" << std::endl;
                exit(EXIT_SUCCESS);
            }

            // some other non-number string.  give error followed by newline
            std::cout << "Invalid input (type 'quit' to exit)" << std::endl;
        }
    }
}

我看到了一些关于为此使用getline 方法的帖子,但是当我尝试它们时它们没有编译,并且我无法找到原始帖子,抱歉。

【问题讨论】:

    标签: c++ error-handling user-input cin


    【解决方案1】:

    最好检查如下:

    // attempt to get the int value from standard input
    if(std::cin >> inputNumerator)
    {
        numerator = inputNumerator;
        break;
    } else { // ...
    

    或者是:按照建议解析完整的输入行,适当地结合std::getline()std::istringstream

    【讨论】:

    • @doctordoder Bwoooah!我的第一枪就这么快,真的吗??
    • 是的,直到 10 分钟过去了,我才接受,每次发生这种情况我都会感到难过。
    • @doctordoder 对你的问题投了赞成票以报复:D! Seriosly:这不是一个非常适合 SO 的问题,而且我的第一枪回答抓住了所有问题表明这一点。但现在让我们都像我们一样快乐;) ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-24
    • 2019-08-02
    • 2016-07-21
    • 1970-01-01
    • 2014-12-18
    • 2018-07-23
    相关资源
    最近更新 更多