簡體   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