为菜单创建基本的用户输入验证(使用基本的 while/do-while 等循环)

Creating rudimentary user input validation for menus (using basic while/do-while etc loops)

本文关键字:while do-while 循环 验证 创建 菜单 用户 输入      更新时间:2023-10-16

我遇到的总体问题:我误解了如何使用循环/if-else-if类型的逻辑正确验证菜单选择中的用户输入。我需要弄清楚我在概念上做错了什么,而不是技术上错了(因为我们有非常具体的规则来指导我们在课堂上如何处理我们的程序)。

问题#1 =程序启动时,用户有两个选项。显然,如果两个选项都没有被选中,则用户输入了无效字符的响应。我的问题是,当我在无效的选择屏幕上时,它只允许我点击"P"开始游戏,而不是"Q"结束游戏。我的循环中的某些内容仅接受"P"作为推动程序前进的有效输入。

我尝试在 do/while 循环和 if/else if 语句之间切换。do/while 循环提供了最少的问题,同时仍然保留了一些问题。

我只在上第二堂编程课,所以我可能无法给出比我尝试不同的循环和移动小段代码更好的详细答案,对不起。

我只会发布程序的int main(),因为它包含我遇到问题的菜单。还有其他函数具有类似问题的用户输入,但是如果我在这里修复我的概念错误,我可以在那里修复它。

int main()
{
char Sel;
int compChoice;
int playerChoice;
cout << "n";
cout << "ROCK PAPER SCISSORS MENU" << endl;
cout << "------------------------" << endl;
cout << "p) Play Game" << endl;
cout << "q) Quit" << endl;
cout << "Please enter your choice:" << endl;
cin >> Sel;
if (Sel == 'q' || Sel == 'Q')
{
cout << "You have chosen to exit, thanks for playing" << endl;
}
do
{
if (Sel == 'p' || Sel == 'P')
{
playerChoice = getPlayerChoice();
compChoice = getComputerChoice();
if (isPlayerWinner(compChoice, playerChoice))
{
cout << "Winner Winner Chicken dinner" << endl;
}
else if (!isPlayerWinner(compChoice, playerChoice))
{
cout << "You lose this round" << endl;
}
else if (isTie(compChoice, playerChoice))
{
cout << "You have Tied" << endl;
}
else
{
cout << "Thanks for playing" << endl;
return 0;
}
}
else
{
cout << "Invalid selection, please try again by hitting 'p' or 'q'." << endl;
cin >> Sel;
}
} while (Sel != 'q' || Sel != 'Q');
system("PAUSE");
return 0;
}

谢谢你的时间!

罪魁祸首是do/while循环末尾的这一行。

while (Sel != 'q' || Sel != 'Q');

应为以下内容。

while (Sel != 'q' && Sel != 'Q');