c++ - 用户输入整数后跟垃圾

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

在我的简单 Fraction类,我有以下方法来获取 numerator 的用户输入,它可以很好地检查像 garbage 这样的垃圾输入, 但不会识别以整数开头且后跟垃圾 1 garbage 的用户输入或 1garbage .

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

关于c++ - 用户输入整数后跟垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21649543/

相关文章:

c++ - 数据类型 inst 转换正确吗?

c++ - 平凡可复制的值表示与可能不可复制的值表示之间是否存在显着差异

scala - 与 IO monads 的普通旧特征相比,Free monads 有什么优势?

python - 处理 argparse 输入中的空格

c++ - mktime 每次返回相同的值

python - 非成员运算符重载(特别是运算符==)在 Cython 中是否被破坏?

c++ - 二维数组中的用户输入 (C++)

c - 读取用户输入,但必须与 C 中的字符串/小数/字符区分开

javascript - 处理循环数组请求错误的问题

bash - 如何在 if 语句中捕获错误