【问题标题】:How do you make a loop with switch statements in c++?如何在 C++ 中使用 switch 语句创建循环?
【发布时间】: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 &gt;&gt; choice 可能会失败,如果流中有意外的内容(例如,某些字母字符在需要数字时无法解析)。 .. 你真的应该说像if (!(cin &gt;&gt; choice)) { std::cerr &lt;&lt; "imvalid choice, terminating\n"; return EXIT_FAILURE; } 这样的话。您的数学/数字游戏也可能是 exit()throw 或 - 如果嵌入在 main() 中而不是在您调用的函数中,请将循环中的 menu 设置为 falsebreak。尝试调试器或随意添加std::cout &lt;&lt; "made it to line " &lt;&lt; __LINE__ &lt;&lt; "\n"; 跟踪。
  • 我看不出你的代码为什么不起作用,事实上它对我有用。这种事情通常表示构建错误。检查你的编译和链接过程。
  • 它确实有效!但我应该添加它。我要添加的是游戏结束后返回主菜单的选项;我必须提示他们:“返回菜单?y/n”等
  • default: menu = false; break;

标签: c++ loops visual-c++ while-loop switch-statement


【解决方案1】:

代码完全符合您的要求!它要求用户提供一个选项,然后,除了选项 3 之外,返回到菜单的开头。

这是因为你有:

bool menu = true;
while (menu) {
   // your print and games
   // no modification of 'menu'
}

还要注意这一点:

cout << setfill(sym) << setw(55);  // 'sym' is NOT initialized here.

【讨论】:

  • 虽然它确实打印回菜单,但我希望能够询问用户是否想在完成游戏后返回菜单,或者退出。 Sym 被声明为 char sym,因为它打印菜单的边框;这只是装饰..如果我不清楚,我很抱歉!
  • 已声明但未初始化。所以你希望用户被询问是退出还是回到菜单的开头@Spacebear5000?你到底想要什么,因为从你的问题中我明白了我写的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多