我的问题:此代码可以使用一次。如果输入有效,则进入下一个cout“输入攻击者数量”。如果输入无效,则会显示错误消息“数字必须为1到5”,但它会在循环中卡住,重复“选择攻击动物”。无论之后的输入如何,它都重复相同。如果输入有效,如何让它继续?
bool validInput = true;
do
{
cout << "Choose your attacking animal:" << endl;
cout << "1 = Bunny, 2 = Chicken, 3 = Kitty, 4 = Puppy, 5 = Wolverine" << endl;
cin >> attacker;
if (attacker < 1 || attacker > 5 || cin.fail())
{
cout << "Number must be 1 through 5" << endl;
cin.clear();
cin.ignore();
validInput = false;
}
} while (!validInput);
cout << "Choose how many " << attacker<< " are attacking"<<endl;
cin >> attNum;
答案 0 :(得分:2)
当validInput失败时,你将validInput设置为false,但是当输入实际上是有效的时,你永远不会将validInput设置为true。
只需在if块中添加一个else块,将validInput设置为true。
答案 1 :(得分:2)
这是因为在第一次使用无效输入的循环中将validInput设置为false后,没有代码在其他尝试中将其设置为true,因此进入无限循环,即while条件总是失败
当答案在有效预期值范围内时,您需要做的是将valdInput设置为true。例如,修改原始代码:
bool validInput = true;
do
{
cout << "Choose your attacking animal:" << endl;
cout << "1 = Bunny, 2 = Chicken, 3 = Kitty, 4 = Puppy, 5 = Wolverine" << endl;
cin >> attacker;
if (attacker < 1 || attacker > 5 || cin.fail())
{
cout << "Number must be 1 through 5" << endl;
cin.clear();
cin.ignore();
validInput = false;
} else {
validInput = true;
}
} while (!validInput);
cout << "Choose how many " << attacker<< " are attacking"<<endl;
cin >> attNum;
如果有帮助,请告诉我。
答案 2 :(得分:2)
正如LarsEggert已经声明的那样,如果输入实际上有效,你永远不会将有效标志设置回true。
我会用以下方式解决它:
bool validInput;
do {
// Assumption: Input will be valid (Loop will not repeat in this case)
validInput = true;
cout << "Choose your attacking animal:" << endl;
cout << "1 = Bunny, 2 = Chicken, 3 = Kitty, 4 = Puppy, 5 = Wolverine" << endl;
cin >> attacker;
// Check if assumption was wrong (Loop will run again in this case)
if (attacker < 1 || attacker > 5 || cin.fail())
{
cout << "Number must be 1 through 5" << endl;
cin.clear();
cin.ignore();
validInput = false;
}
} while (!validInput);
cout << "Choose how many " << attacker<< " are attacking"<<endl;
cin >> attNum;
与Jorge Torres的答案相比,你不必编写其他案例。
我通常按照这种形式进行循环:
bool repeat;
do {
repeat = false
// do something
// if loop has to be repeated, just set repeat = true somewhere here
} while(repeat);
这样你就不会在你的时间里有一个否定,你也只需要关注必须设置repeat-flag的情况。
答案 3 :(得分:1)
这是因为如果输入错误,则不会从输入缓冲区中提取和删除它,并且因为您在没有参数的情况下调用std::istream::ignore
,所以只从无效输入中提取单个字符,如果输入后输入的数据无效然后你的下一个输入将会读取它。
您可以使用std::istream::ignore
提取(并丢弃)输入,直到下一个换行符为止:
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');