Как заставить оператор switch вернуться в меню?

0

Привет всем, у меня в настоящее время возникают проблемы с тем, чтобы заставить оператор switch вернуться к началу меню. Вместо этого он переходит к другой основной функции, которую я не хочу, если пользователь не выберет правильный выбор.

вот код, который у меня есть:

int main() 
{
int choice;
bool menu = true;
cout <<"Please select one of the following options:  \n";

cout << "1: Play\n"
        "2: Help\n"
        "3: Config\n"
        "4: Quit\n";

cout << "Enter your selection (1, 2,3 or 4): ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
    if(menu)
    {

      switch (choice)
     {
          case 1:
            cout << "You have chosen play";
            break;
         case 2:
            cout << "You have chosen help\n";
            cout << "Here is a description of the game Hangman and how it is played:\nThe word to guess is represented by a row of dashes, giving the number of letters, numbers and category. If the guessing player suggests a letter or number which occurs in the word, the other player writes it in all its correct positions";
            break; 
         case 3:
            cout << "You have chosen config";
            break;
             case 4:
            cout << "You have chosen Quit, Goodbye.";
            break;
        default:
            cout<< "Your selection must be between 1 and 4!\n";

    }

        }    
getchar();
getchar();


cout << "You missed " << playGame("programming");
cout << " times to guess the word programming." << endl;

}

Теги:

2 ответа

0
Лучший ответ

вы можете использовать цикл do while while следующим образом:

int main() 
{
int choice;
bool menu = true;
do{
cout <<"Please select one of the following options:  \n";

cout << "1: Play\n"
    "2: Help\n"
    "3: Config\n"
    "4: Quit\n";

cout << "Enter your selection (1, 2,3 or 4): ";
cin >> choice;
//*****************************************************************************
// Switch menu to display the menu.
//*****************************************************************************
    switch (choice)
 {
      case 1:
        cout << "You have chosen play";
       int missed = playgame('programming');
        break;
     case 2:
        cout << "You have chosen help\n";
        cout << "Here is a description of the game Hangman and how it is    played:\nThe      word to guess is represented by a row of dashes, giving the number of letters, numbers and category. If the guessing player suggests a letter or number which occurs in the word, the other player writes it in all its correct positions";
        break; 
     case 3:
        cout << "You have chosen config";
        break;
         case 4:
        cout << "You have chosen Quit, Goodbye.";
        break;
    default:
        cout<< "Your selection must be between 1 and 4!\n";

    }

}while(choice!=4);    
getchar();
getchar();


cout << "You missed " << playGame("programming");
cout << " times to guess the word programming." << endl;

}

Я добавил цикл do перед отображением вашего меню, чтобы каждый раз, когда пользователь выбирал выбор, пользователь снова отображает меню, если пользователь не вводит 4, и в этом случае программа выходит из цикла do while. Вы можете вызвать функцию playgame() в случае 1.. Я отредактировал свой ответ, чтобы включить playgame();

  • 0
    Итак, у меня есть более ранняя функция int playGame (); Я бы просто вызвал функцию в случае 1: или есть какой-то другой метод, чтобы получить код для игры? Извините, я сейчас очень смущен.
  • 0
    @ user2857301 вы можете вызвать функцию в случае 1, как показано выше
2

Вы можете заменить ваш, if с в while цикла

cout << "Enter your selection (1, 2, 3 or 4): ";
while (menu)
{
    cin >> choice;
    menu = false;

    switch (choice)
    {
    case 1:
        cout << "You have chosen play";
        break;
    ....
    default:
        cout<< "Your selection must be between 1 and 4!\n";
        menu = true; // incorrect input, run loop again
}

Ещё вопросы

Сообщество Overcoder
Наверх
Меню