Matt
Matt

Reputation: 21

C++ switch in loop goes to default before running again

My first program in C++ is a command line survival game. I have a switch statement in a while loop, but it always goes through once and runs the default choice before getting the users input. Here's the relevant code:

int menu() {
    while (true) {
        char choice = getChoice();
        switch(choice) {
            case 'p':
            {
                system("clear");
                Arena arena(player, difficulty);
                arena.play();
            }
                break;
            case 'u': 
            {
                system("clear");
                player.save();
                player.init();
            }
                break;
            case 'd': 
            {
                system("clear");
                changeDifficulty();
            }
                break;
            case 'q':
            {
                system("clear");
                return 0;  // return menu(); in main()
            }
            default:
            {
                system("clear");
                cout << nInvalid option! Press a key to choose: p, u, s, or q\n\n";
                break;
            }
        }
    }
}

getChoice Function

char getChoice() {

    cout << "      Main Menu\n";
    cout << "---------------------\n";
    cout << "p - play game" << endl;
    cout << "u - change user" << endl;
    cout << "d - change difficulty" << endl;
    cout << "q - quit\n" << endl;

    char choice = getchar();
    return choice;
}

Everything works fine after it goes through once and runs the code from the default option. Here's what I get every time the program re-enters this loop:

Invalid option! Press a key to choose: p, u, s, or q

      Main Menu
---------------------
p - play game
u - change user
d - change difficulty
q - quit

Thanks for any help in advance!

Upvotes: 0

Views: 98

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409364

Assuming you use the standard getchar function.

The problem is most likely that when you enter your "choice" you enter the 'p' (for example) and then press the Enter key. That Enter key will also be in the input as a newline '\n'. So the next time you call getChoice (and it calls getchar) you read that newline.

There are basically four ways to solve it:

  1. The C way, using scanf instead of getchar, and ask scanf to read and discard leading whitespace (like newlines):

    char choice;
    scanf(" %c", &choice);
    // Note space in front of the %c, which tells scanf to discard leading whitespace
    
  2. Read the character, and then read and discard everything else until the newline.

  3. Read the whole line into a string, and the parse out the character.

  4. Use std::cin and the normal formatted input operator >>, as that will skip leading whitespace.

I really recommend the last (number 4) method.

Upvotes: 3

Related Questions