Search code examples
cswitch-statementgetchar

C: Problems with using getchar and switch case to get user input for a main menu


I know there are many threads similar to this one, however, those threads didn't really help me out. I am new to C, so I might be just making a silly mistake, but I don't know what I'm doing wrong.

I am trying to create a main menu like this:

Main menu:

1. Play
2. Reset
3. Display

When users press 1, I want it to print play game, when 2 is pressed, I want it to print Reset, and so on.
However, with my code, when user presses 1, it prints "play game", and when users presses 2 or 3, it doesn't print anything.

int main(){

    int input;

    /*Displays the menu to user*/

    printf("Main menu\n");
    printf("1.Play\n");
    printf("2.Reset\n");
    printf("3.Display\n");   
    printf("please enter something:\n");

    input=getchar();

    switch(input){
    case'1':
        printf("play game\n");
        break;
    case'2':
        printf("reset\n");
        break;
    case'3':
        printf("Display\n");   
        break;
    default:
        printf("invalid\n");
        break;
    }

    {
        getchar();
        while(input != '3');
    }
    return EXIT_SUCCESS;
}

So I know I might be making a silly mistake, but I just can't figure what I am doing wrong. I have also looked at other threads and none them have helped me.


Solution

  • I think you are looking for do-while loop. You want to nest your switch inside this do-while to repeatedly execute it.

    Also, note the extra getchar() call to consume the Enter that was typed after the number.

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(){
    
        int input;
    
        /*Displays the menu to user*/
    
        printf("Main menu\n");
        printf("1.Play\n");
        printf("2.Reset\n");
        printf("3.Display\n");   
        printf("please enter something:\n");
    
    
        do{
            input=getchar();
            getchar();
            switch(input){
                case'1':
                    printf("play game\n");
                    break;
                case'2':
                    printf("reset\n");
                    break;
                case'3':
                    printf("Display\n");   
                    break;
                default:
                    printf("invalid\n");
                    break;
            }
    
        } while(input != '3');
        return EXIT_SUCCESS;
    }