【发布时间】:2020-04-15 22:38:10
【问题描述】:
我有一些循环问题。我正在尝试循环多个语句。代码如下。
int MenuSelect () {
cout << endl;
cout << YELLOW << "Enter 1 for info" << endl;
cout << " " << endl;
cout << "Enter 2 to Start" << endl;
cout << " " << endl;
cout << "Enter 3 to view settings" << endl;
cout << " " << endl;
cout << "Enter 4 to quit" << endl;
int selected = 0;
string input;
cin >> input;
if (stringstream(input) >> selected) {
return selected;
}
else {
return -1;
}
return 0;
};
int Menu(int) {
int selected {};
while ((selected = MenuSelect()) == 1) {
printmessage();
}
if (selected == 3) {
cout << "Current Settings" << endl;
somefunction();
}
else if (selected == 2) {
cout << "Starting Game..... " << endl;
}
else if (selected == 4) {
cout << "Exiting....." << endl;
exit (3);
}
else {
cout << "Invalid Entry" << endl;
exit (3);
}
cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;
return 0;
};
所以你可以看到用户可以看到菜单,然后 if 和 else 语句完成工作。目前我已经设法循环第一个菜单选择,所以如果用户输入 1 它将打印消息然后循环回菜单。我想要的是还循环 3 - 当前设置,如果用户输入无效数字。我试图完成它,但我似乎做不到。
【问题讨论】:
-
将那些
if/else if块移动到循环体中,然后将循环条件更改为while ((selected = MenuSelect()) > 0)(在这种情况下有效,因为您的4案例只调用exit),或者将selected = MenuSelect()拉出循环并在循环体的末尾再次运行。 -
@0x5453 谢谢你解决了这个问题
标签: c++ loops while-loop