忍耐與我,我還是很新的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循環,但我不知道如何去做。我很感激任何建議!
怎麼樣',而(真){...}' – 2014-10-31 03:58:40
唯一的相關問題與你的代碼」已發佈的是,如果流中有意想不到的東西(例如一些字母字符在預期數字時不能被分析),'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
我沒有看到你的代碼無法正常工作的原因,事實上它確實對我有用。這種事情通常表示構建錯誤。檢查你的編譯和鏈接過程。 – 2014-10-31 04:20:41