[英]Getting loop to redisplay message c++
我试图让一个程序来显示一个带有选项的菜单,然后给定用户输入,显示某个消息。 在显示他们的消息后,我希望循环返回显示消息,直到他们选择退出选项。 在选择 1-3 后,如何让循环返回显示菜单?
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
int menu_choice;
cout << "Select a numerical option:" << endl << "=== menu ===" << endl << "1. Fox" << endl << "2. Bunny" << endl << "3. Sloth" << endl << "4. Quit" << endl;
cin >> menu_choice;
while (menu_choice >= 1 && menu_choice <= 4)
{
while (menu_choice == 1)
{
cout << "1 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 2)
{
cout << "2 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 3)
{
cout << "3 work" << endl;
menu_choice = 0;
continue;
}
while (menu_choice == 4)
{
cout << "4 work" << endl;
menu_choice = 0;
continue;
}
}
return 0;
}
您的代码仅显示菜单 1 次。 如果用户输入了无效的选项,您将立即退出。 如果用户输入了一个有效的选项,你就完成了选择的工作,但随后你退出而不是再次显示菜单。 你所有的while..continue
循环完全没用,它们最多只运行 1 次,将menu_choice
设置为 0,这会破坏你的外部while
循环,因此它也只运行 1 次。
您需要一个连续运行的外循环,每次都显示菜单,直到您真正准备好退出。
您还应该用if/else
块或更好的单个switch
块替换无用的while..continue
循环。
尝试更像这样的事情:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
int menu_choice;
do
{
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if (!(cin >> menu_choice))
{
menu_choice = 0;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
switch (menu_choice)
{
case 1:
cout << "1 work" << endl;
break;
case 2:
cout << "2 work" << endl;
break;
case 3:
cout << "3 work" << endl;
break;
case 4:
cout << "4 work" << endl;
break;
default:
cout << "Bad choice! Try again" << endl;
break;
}
}
while (menu_choice != 4);
return 0;
}
我真的不认为你在这个问题上需要帮助,所以我有点不愿意写这个答案^^。
重复选择通常以这种方式实现:
while (someCondition) { // goes out if the condition isn't met
cout << "The question" << endl;
cin >> theAnswer;
if (theAnswer == 1) { // check the answer
// do something
}
// probably other checks
}
我建议你先在小程序中用if和while练习一下,比如问年龄,或者计算斐波那契列表
@Remy Lebeau 的发布速度更快,他的回答写得很好,但由于我已经完成了代码的编写,您可能会受益于查看不同的实现,我发布了代码。 我故意选择不使用 switch,因为你之前可能没有见过它。
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
bool quit = false;
int menu_choice;
while(!quit) {
cout << "Select a numerical option:" << endl
<< "=== menu ===" << endl
<< "1. Fox" << endl
<< "2. Bunny" << endl
<< "3. Sloth" << endl
<< "4. Quit" << endl;
if(cin >> menu_choice) {
if(menu_choice == 1) {
cout << "1 work" << endl;
}
if(menu_choice == 2) {
cout << "2 work" << endl;
}
if(menu_choice == 3) {
cout << "3 work" << endl;
}
if(menu_choice == 4) {
cout << "Bye" << endl;
quit = true; // Set quit to true to stop the while loop
} else {
cout << "Invalid number" << endl;
}
} else {
cout << "Bad input" << endl;
cin.clear();
cin.ignore();
}
}
return 0;
}
请注意, cin.ignore
和cin.clear
很重要,并且经常使不cin.clear
这一点的人cin.clear
困惑。 阅读这个问题了解详情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.