繁体   English   中英

如何使用C ++中的switch语句进行循环?

[英]How do you make a loop with switch statements in c++?

忍受我,我还是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;
    }
  }
}

我已经省略了游戏本身,但是我对如何在完成游戏后从两个游戏返回到主菜单感到困惑。 完成后,我将提示用户“返回菜单?是/否”。 我怀疑我必须插入一个do-while循环,但是我不确定该怎么做。 我感谢任何建议!

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

这是因为您有:

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

另请注意:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM