Search code examples
c++switch-statementdefault

C++ Switch Statement - Giving player another chance to choice


This is a block of code from a book I've been studying and trying to improve upon, but I'm having trouble finding a way to give the player another chance at selecting the difficulty after entering the default choice. This is a very simple console text-based game and when the player chooses an incorrect choice, the game doesn't allow the player to re-choose.

 int _tmain(int argc, _TCHAR* argv[])
 {
     cout << "Difficulty Levels\n\n";
     cout << "1 - Easy\n";
     cout << "2 - Normal\n";
     cout << "3 - Hard\n\n";

     int choice;
     cout << "Choice: ";
     cin >> choice;


     switch (choice)
     {
      case 1:
         cout << "You picked Easy\n";
         break;
     case 2:
         cout << "You picked Normal\n";
         break;
     case 3:
         cout << "You picked Hard\n";
         break;
     default:
         cout << "Your choice is invalid.\n";
     }

     system("pause");
     return 0;
 }

Solution

  • You can refactor the switch into a function, which can be called whenever the player wants to change their difficulty choice.

    int choose()
    {
        int choice;
        cout << "Difficulty Levels\n\n";
        cout << "1 - Easy\n";
        cout << "2 - Normal\n";
        cout << "3 - Hard\n\n";
    
        cout << "Choice: ";
        cin >> choice;
    
        switch (choice)
        {
         case 1:
            cout << "You picked Easy\n";
            break;
        case 2:
            cout << "You picked Normal\n";
            break;
        case 3:
            cout << "You picked Hard\n";
            break;
        default:
            cout << "Your choice is invalid.\n";
            choice = 0; //this will signal error
        }
        return choice;
    }
    
    int _tmain(int argc, _TCHAR* argv[])
    {
        int choice = 0;
        while(choice == 0){choice = choose();};  
        system("pause");
        return 0;
    }
    

    Now whenever the player decides to change difficulty (maybe they enter a special letter) you can use choice = choose() to alter the difficulty.