首页 > 解决方案 > 我的 while 循环条件没有像我预期的那样评估它们

问题描述

我正在尝试创建一个输入验证函数来检查 cin 是否失败(这工作正常),我还试图让它检查它是否在我通过变量传递给函数的最小最大范围内。

我已经尝试过处理不同的条件并手动评估它,但似乎我错过了 while 循环的一些小细节或完全不同的东西。

void isValid(int &value, std::string message, int min, int max) {
    while(((std::cout << message) && !(std::cin >> value)) && ((value >= min) && (value <= max))) {
        std::cout << "Error with input" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<int>::max(), '\n'); }

我希望 isValid(-1, "Enter the test score: ", 0, 100) 的输出继续要求输入有效,但它按原样接受它。

标签: c++

解决方案


我认为您在有条件的循环中尝试做太多事情。这一点的证据是,您——作者,以及最有可能一眼看懂代码的人——对布尔逻辑感到困惑。

为了使逻辑更简单、更易读、更正确,我们可以应用关注点分离的原则将代码分成两部分:一部分负责获取输入,另一部分负责处理失败时的情况:

// returns true if a valid value entered, false if invalid or I/O error
bool getInput(int& value, const std::string& message, int min, int max) {
    if (!(std::cout << message)) return false;
    if (!(std::cin >> value)) return false;
    return value >= min && value <= max;
}

void getValidInput(int& value, std::string message, int min, int max) {
    while (!getInput(value, message, min, max)) {
        std::cout << "Error with input" << std::endl;
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<int>::max(), '\n'); }
    }
}

如果std::cout有错误重试是可疑的;重试不太可能成功,这可能意味着您的程序有问题。您可能会考虑在这里抛出异常。


推荐阅读