2014-10-31 97 views
0

忍耐与我,我还是很新的C + + ...如何用C++中的switch语句做一个循环?

所以我的困境是,我有一个菜单2场比赛,都在其各自的switch语句/案件。该代码有效,但一旦完成,它就会关闭游戏。我不能为了我的生活找出如何循环回到我再次选择游戏的主菜单。

我的代码如下:

#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

怎么样',而(真){...}' – 2014-10-31 03:58:40

+0

唯一的相关问题与你的代码”已发布的是,如果流中有意想不到的东西(例如一些字母字符在预期数字时不能被分析),'cin >> choice'可能会失败......你应该真的说'if(!(cin >>选择)){std :: cerr <<“无效的选择,终止\ n”;返回EXIT_FAILURE; }'。你的数学/数字游戏也可能是'exit()','throw'或者 - 如果嵌入在main()中,而不是在你调用的函数中,将'menu'设置为'false'或'break'。尝试一个调试器或宽松地添加'std :: cout <<“使其成为”<< __LINE__ <<“\ n”; trace。 – 2014-10-31 04:20:01

+0

我没有看到你的代码无法正常工作的原因,事实上它确实对我有用。这种事情通常表示构建错误。检查你的编译和链接过程。 – 2014-10-31 04:20:41

回答

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. 
+0

虽然它打印回菜单,但我希望能够询问用户是否想在游戏结束后返回到菜单,或者退出。 Sym被声明为char sym,因为它打印菜单的边框;这只是装饰..如果我不清楚,我很抱歉! – Spacebear5000 2014-10-31 04:26:12

+0

已声明但未初始化。所以你希望询问用户是否退出或回到菜单@ Spacebear5000的开始?你究竟想要什么,因为从你的问题我明白我写的东西。 – gsamaras 2014-10-31 04:29:47