用户输入整数后跟垃圾



在我的简单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 方法的帖子,但是当我尝试它们时它们没有编译,而且我找不到原始帖子,抱歉。

最好检查如下:

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

或者:按照建议正确解析组合std::getline()std::istringstream的完整输入行。

相关内容

  • 没有找到相关文章