2014-10-31 100 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