我试图将程序中的硬编码数减至最少,并允许用户定义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或更小的最大值。
最佳答案
do
{
//ask for input
//input taken
} while (A>=1);
这将是您在最后一行中描述的方案必须使用的代码。还有一点,您只是忘记根据逻辑将任何值分配给A。谢谢!
关于c++ - 使用do while循环验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63124444/