我对循环有一些问题。我正在尝试循环多个语句。代码如下。
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-当前设置,如果用户输入一个无效的数字。我试过了,但似乎做不到。
发布于 2020-04-15 22:38:11
您可能希望重复读取用户输入并做出相应的反应?您可以将所有的if放入while中
int Menu(int) {
int selected {};
bool loop = true;
while (loop) {
selected = MenuSelect();
if(selected == 1) {
printmessage();
}
else if (selected == 3) {
cout << "Current Settings" << endl;
somefunction();
}
else if (selected == 2) {
cout << "Starting Game..... " << endl;
}
else if (selected == 4) {
cout << "Exiting....." << endl;
loop = false;
}
else {
cout << "Invalid Entry" << endl;
loop = false;
}
}
cout << "Below is the Deck of cards and you will get to choose 5 cards to play with. Choose wisely." << endl;
return 0;
};使用变量loop退出while只是个人喜好,您可能会有一个无限的循环
while(true)然后使用break;退出循环,或者使用exit()退出整个程序,就像现在一样。
https://stackoverflow.com/questions/61231102
复制相似问题