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

时间:2018-06-16 14:33:18

标签: c++ input int cin

我试图只允许输入整合器

应该拒绝:

  • 5H
  • 3.4
  • 3.gh
  • 3.0
  • HTR

应该接受:

  • -5
  • 0
  • 78

当前代码

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;
}

更新代码

的问题:

  • 接受除“htr”(无数字)之外的所有拒绝

    int getIntInput() {
            std::string rawInput;
            int parsedinput;
    
            while (true) {
                std::cout << "> ";
                std::getline(std::cin, rawInput);
                std::cout << std::flush;
    
                try {
                    parsedinput = std::stoi(rawInput);
    
                } catch (std::invalid_argument & e) {
                    continue;
    
                } catch (std::out_of_range & e) {
                    continue;
                }
    
               break;
        }
        return parsedinput;
    }
    

完成代码

  • 仅接受带有可选参数的整数 负数被接受或拒绝。

    int getIntInput(bool allowNegatives = true) {
        bool validIntInput;
        std::string rawInput;
        int parsedinput;
    
        while (true) {
            validIntInput = true;
    
            // Grabs the entire input line
            std::cout << "> ";
            std::getline(std::cin, rawInput);
            std::cout << std::flush;
    
            for (int i = 0; i < rawInput.length(); i++) {
                // Checks to see if all digits are a number as well as to see if the number is a negative number
                if (!isdigit(rawInput[i]) && !(allowNegatives && i == 0 && rawInput[i] == '-')) {
                    validIntInput = false;
                    break;
                }
            }
    
            if (!validIntInput) {
                continue;
    
            } else {
                try {
                    // Try parse the string to an int
                    parsedinput = std::stoi(rawInput);
    
                    // Catch all possible exceptions, another input will be required
                } catch (...) {
                    continue;
                }
                // If the code reaches here then the string has been parsed to an int
                break;
            }
        }
        return  parsedinput;}
    

3 个答案:

答案 0 :(得分:2)

当必须读取int时,cin的工作方式是它开始解析整数并在找到非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库)

答案 1 :(得分:2)

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

您需要#include isdigit()的cctype。

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

答案 2 :(得分:0)

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);