【发布时间】:2014-07-01 08:01:49
【问题描述】:
嗨,我是 C++ 新手,我不明白为什么我的 while 语句现在不起作用。当我早些时候尝试这样做时,它正在工作。
完整代码见:http://pastebin.com/aeH5fKwh
这里基本上是while循环(我排除了所有不必要的部分,为了查看目的,我保留了while循环的内部)
int main()
{
unsigned int seed;
char input;
bool done;
for (int round = 0; round < 5; round++)
{
done = false;
cout << "\nEnter seed: ";
cin >> seed;
cout << "\nRound 1" << endl;
while(!done)
{
cout << "\nDo you wish to draw another card [y][n]: ";
cin >> input;
while (input != 'y' && input != 'n')
{
cout << "Invalid input! Please enter [y][n]!" << endl;
cin >> input;
}
if (input == 'y')
{
dealExtra(playerHand, deck, gameInfo);
cout << "Your cards are ";
printHand(playerHand, gameInfo.playerCardCount);
}
else
done = true;
}
}
cout << endl;
return 0;
}
当我尝试输入任何不是“y”、“n”的内容时,它会告诉我我的输入无效。但是当我尝试输入 'y' 或 'n' 时,它只是忽略了它,没有发生任何其他事情。我检查了 cout 语句,发现它设法进入 if (input == 'y') 语句,但它似乎没有做任何其他事情。直到 20 分钟前一切都很好,我真的不知道出了什么问题。
编辑:我使用 "cout
Do you wish to draw another card [y][n]: y
[y]
y
y
y
y
我使用 g++ 在 linux 终端上编译了这个
如果需要额外的代码,我会编辑并添加它们。谢谢!
【问题讨论】:
-
您没有检查输入错误。此外,可能有输入缓冲处于活动状态。无论如何,在寻求帮助时,请始终尝试提供一个最小的、可编译的示例来展示您的错误。我建议阅读 How to Debug Small Programs 以更好地了解如何调试它。
-
内部 while 循环的逻辑条件应该多考虑一点,通过手动跟踪不同的输入值并生成逻辑表。了解 C++ 如何短路逻辑条件也将有所帮助。请参阅此内容以供参考:Logical operators
-
我已按照建议编辑了这篇文章.. 并将完整的代码包含在 pastebin 链接中,以防万一它有帮助.. 同时,我会照你说的做,看看调试小程序指南..谢谢
-
it kinda just ignored it and nothing else happened和it doesnt seem like it is doing anything else是非常模糊的陈述。你到底是什么意思? -
是的。我不明白为什么它在 30 分钟前工作正常时忽略了我的输入。我根本没有编辑该部分。我尝试使用 cout 和 cerr 语句来确保它确实到达了我想要它去的地方..
标签: c++