仅获取整数作为输入,代码未按预期工作

Get only integers as input, code not working as expected

我试图只允许输入整数

应该拒绝:

应该接受:

当前代码

int getIntInput() {
    int userInput;

    while (true) {
        std::cout << "> ";
        std::cin >> userInput;
        std::cout << std::flush;

        if (std::cin.fail()) {
            std::string cinBuffer;
            std::cin.clear();
            std::getline(std::cin, cinBuffer);
            continue;
        }
        break;
    }
    return userInput;
}

更新代码

问题:

完成代码

cin 在必须读取 int 时的工作方式是,它开始解析整数并在找到非 int 字符时停止,将解析的 int 存储在变量中。这就是为什么在浮点数上它停在点上,而在输入“5g”中它将停在 g 上。

如果您只想输入整数,您可以做的是 read the whole line 然后检查字符串中的每个字符是否都是数字,使用以下代码:

bool onlyNums = true;
for (int i=0;i<rawInput.size();i++) {
    if (!isdigit(rawInput[i]))
        onlyNums = false;
}

if (!onlyNums)
    continue;

(您必须为上述代码包含 ctype.h 库)

如果您不介意开销,我会使用 cin.getline() 从 cin 获取输入并将其保存为字符串。然后遍历字符串并在每个字符上调用 isdigit 。您可以使用 str.erase 函数丢弃不是数字的字符。

您需要为 isdigit() #include cctype。

注意:根据字符串的长度,这至少需要 O(N) 的运行时间。

template<class T>
T findInStreamLineWith(std::istream &input) {
    std::string line;
    while (std::getline(input, line)) {
        std::istringstream stream(line);
        T x;
        if (stream >> x >> std::ws && stream.eof()) {
            return x;
        }
        // reenter value
        // cout << "Enter value again: ";
    }
    throw std::invalid_argument("can't find value in stream");
}

…
auto x = findInStreamLineWith<int>(std::cin);