【发布时间】:2014-12-27 08:01:57
【问题描述】:
请耐心等待,我对 C++ 还是很陌生...
所以我的困境是我有两个游戏的菜单,都在它们各自的 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 循环,但我不确定如何去做。我很感激任何建议!
【问题讨论】:
-
while(true){ ... }怎么样 -
与您发布的代码唯一相关的问题是
cin >> choice可能会失败,如果流中有意外的内容(例如,某些字母字符在需要数字时无法解析)。 .. 你真的应该说像if (!(cin >> choice)) { std::cerr << "imvalid choice, terminating\n"; return EXIT_FAILURE; }这样的话。您的数学/数字游戏也可能是exit()、throw或 - 如果嵌入在main()中而不是在您调用的函数中,请将循环中的menu设置为false或break。尝试调试器或随意添加std::cout << "made it to line " << __LINE__ << "\n";跟踪。 -
我看不出你的代码为什么不起作用,事实上它对我有用。这种事情通常表示构建错误。检查你的编译和链接过程。
-
它确实有效!但我应该添加它。我要添加的是游戏结束后返回主菜单的选项;我必须提示他们:“返回菜单?y/n”等
-
default: menu = false; break;
标签: c++ loops visual-c++ while-loop switch-statement