问题描述
我试图获取一个程序来显示带有选项的菜单,然后在用户输入的情况下显示某些消息。在显示他们的消息之后,我希望循环返回到显示消息,直到他们选择退出选项为止。如何选择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次。
您需要一个连续运行的外部循环,每次显示菜单,直到您真正准备退出为止。
您还应该将无用的while..continue
循环替换为if/else
块,或者最好将单个switch
块替换掉。
尝试更多类似方法:
#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
}
我建议您先在小程序中练习是否需要,例如问年龄或计算纤维绒布清单
,@Remy Lebeau发帖更快,他的回答写得很好,但是由于我写完了代码,您可能会发现在我发布代码的各种实现中受益。我特意选择不使用开关,因为您以前可能没有看过它。
#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
很重要,并且常常使新手感到困惑。详细阅读this question。