忍受我,我还是C ++的新手......
所以我的困境是我有两个游戏的菜单,都在他们各自的开关声明/案例中。代码有效,但一旦完成,它就会关闭游戏。我不能为我的生活弄清楚如何循环回到我再次选择游戏的主菜单。
我的代码如下:
#include<iostream>
#include<string>
#include<cstdlib>
#include<ctime>
#include<iomanip>
using namespace std;
int main()
{
string name;
int choice; //the choices for the menu
char sym; //part of the menu
int number = rand() % 10 + 1; //sets number to a random number between 1-10
int digit; // part of the math game
bool menu = true;
int guessNum; //number that user guesses
int i; //loop variable
bool guessRight = false;
char answer = 'y';
/questions omitted
while (menu){ //start of loop and will come back here after each game finishes
cout << setfill(sym) << setw(55);
cout << "\n";
cout << "\t Welcome," << ' ' << name << endl;
cout << "Please choose a number from the following options:" << endl; //Gives the user the options to input using numbers.
cout << "\n";
cout << "\t1. Play the math game!" << endl;
cout << "\t2. Play the guessing game!" << endl;
cout << "\t3. Exit" << endl;
cout << setfill(sym) << setw(55);
cout << "\n";
cin >> choice; //The user gets to input numbers 1-3 at this point
switch (choice)
{
case 1:
//Math game here
break;
case 2:
//random number game here
break;
case 3: //exits the program
cout << "I guess we're done here." << endl;
return 0;
}
}
}
我自己省略了游戏,但我很困惑如何在游戏结束后从两个游戏循环回主菜单。一旦完成,我将提示用户“返回菜单?y / n”。我怀疑我必须插入一个do-while循环,但我不知道如何去做。我很感激任何建议!
答案 0 :(得分:0)
代码完全符合您的要求!它要求用户提供一个选项,然后,除了给出选项3,返回到菜单的开头。
这是因为你有:
bool menu = true;
while (menu) {
// your print and games
// no modification of 'menu'
}
另请注意:
cout << setfill(sym) << setw(55); // 'sym' is NOT initialized here.