使用do while循环验证输入

时间:2020-07-27 22:21:22

标签: c++ loops do-while

我正在尝试最小化程序中的硬编码数量,并允许用户定义max和min参数,并确保输入有效。

#include <iostream>   

int main(){ 
    int max, A=0;
    do
    {
        std::cout << "What is the max?\n";
        std::cin >> max;
        if (std::cin.fail()) {
          std::cin.clear();      
          std::cin.ignore();
          std::cout << "not an integer, try again\n";
          continue;
        }
        if(max < -1000){
            std::cout << "That doesnt make much sense, please enter the max again.\n";
        }
    } while (max <A); \\HERE IS WHERE THE PROBLEM IS.
    std::cout << "The max number of steps are " << max <<std::endl;
    return 0;
    }

如果A为0或更小,则程序不再要求用户输入。相反,程序只是退出循环。 如果A为1或更大,则程序将循环运行,直到提供有效输入为止。

我希望最大数字为任何整数,包括负数。这适用于正数,但不适用于0或更小的最大值。

3 个答案:

答案 0 :(得分:1)

 do
{
  //ask for input      
  //input taken

} while (A>=1); 

这将是您在最后一行中描述的方案必须使用的代码。还有一点,您只是忘记根据逻辑将任何值分配给A。

谢谢!

答案 1 :(得分:0)

如果A为1或更大,则程序将循环运行,直到提供有效输入为止。-您正在说的是while循环需要做什么。只需实施即可。

} while (A >= 1); \\If A is greater than or equal to 1 then loop until valid.
    std::cout << "The max number of steps are " << max <<std::endl;
    return 0;
    }

要回答您的后续问题:

} while (A >= 1 && max <= 0); \\If A is greater than or equal to 1 then loop until valid.
    std::cout << "The max number of steps are " << max <<std::endl;
    return 0;
    }

答案 2 :(得分:0)

我建议编写一个自定义函数,该函数接受可接受的最小/最大值范围作为输入参数,例如:

int promptForInt(const string &prompt, int minAllowed, int maxAllowed)
{
    int value;

    std::cout << prompt << "\n";

    do
    {
        if (!(std::cin >> value)) {
            std::cin.clear();      
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
            std::cout << "not an integer, try again\n";
            continue;
        }

        if ((value >= minAllowed) && (value <= maxAllowed)){
            break;
        }

        std::cout << "not an allowed integer, enter a value between " << minAllowed << " and " << maxAllowed << ".\n";
    }
    while (true);

    return value;
}

int main(){ 
    int max = promptForInt("What is the max?", -1000, 1000);
    std::cout << "The max number of steps are " << max << std::endl;
    return 0;
}