为菜单创建基本的用户输入验证(使用基本的 while/do-while 等循环)
Creating rudimentary user input validation for menus (using basic while/do-while etc loops)
我遇到的总体问题:我误解了如何使用循环/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');
相关文章:
- 为什么"do while"循环不断退出,即使条件计算结果为 false?
- 如果条件为TRUE(最佳方式?),则在do while循环中后置增量
- 即使没有满足他们的条件,我也无法通过一些 do-while 循环
- 如何使用 do while 循环确定最高值和最低值
- do while 循环中的 if 语句以 yes 或 no 结尾
- 使用 while 或 do while 退出循环
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 为什么我的 Do-while 循环无法在C++中运行菜单
- 如果语句不会在 do - while 循环中运行
- 如何在c++中读取do-while循环中的空白
- 什么是'do while loop'的真实应用?
- 将嵌套的 for 循环更改为 do-while 循环
- 如何修复不会在退出选择时终止的 do-while 循环
- 为什么这个do-while循环每隔一个循环只写入数组?
- C++ do/while 循环和 if/else: 骰子游戏 -- 第 75 行错误:"Cout"之前的预期"While" -- 如何解决这个问题?
- 卡在链表中的无限 Do-while 循环中
- 为菜单创建基本的用户输入验证(使用基本的 while/do-while 等循环)
- 使用 while / do-while 循环进行数组元素设置
- 为什么 for/while/do-while 在执行相同的任务时被放置在 c/c++ 中