Search code examples
cinputmenuinfinite-loopdo-while

How to stop an infinite loop after a wrong input in a menu?


i was making a menu with 3 int choices, if the input is a wrong int it reprints the menu and the input. The problem is that when instead of an integer the input is a char the program get stuck in an infinite loop, how can i solve this?


#include <stdio.h>
#include <stdlib.h>

int main(){
    
    int menu_choice;

do{
    printf("\n\t\t...PHALSOPHOBIA...\t\t");
    printf("\n\tMenu\t\n1. Imposta gioco.\n2. Gioca\n3. Termina gioco\n");

    scanf("%d", &menu_choice);

    switch (menu_choice)
        {
        case 1:
        break;

        case 2:
        break;

        case 3:
        break;

        default:
            printf("Comando errato.\n");
        }
}while (menu_choice < 1 || menu_choice > 3);
}

Solution

  • You need to clear the input buffer if it doesn't contain a digit, and you probably want to handle EOF:

    #include <stdio.h>
    #include <stdlib.h>
    
    int flush() {
        for(;;) { int ch = getchar();
            if(ch == EOF || ch == '\n')
                return ch;
        }
    }
    
    int main(){
        int menu_choice;
        do {
            printf("\n\t\t...PHALSOPHOBIA...\t\t");
            printf("\n\tMenu\t\n1. Imposta gioco.\n2. Gioca\n3. Termina gioco\n");
            if(scanf("%d", &menu_choice) != 1) {
                if(flush() == EOF)
                    break;
                menu_choice = 0;
            }
            switch (menu_choice) {
                case 1:
                case 2:
                case 3:
                    break;
                default:
                    printf("Comando errato.\n");
            }
        } while (menu_choice < 1 || menu_choice > 3);
    }
    

    example session:

                    ...PHALSOPHOBIA...
            Menu
    1. Imposta gioco.
    2. Gioca
    3. Termina gioco
    x
    Comando errato.
    
                    ...PHALSOPHOBIA...
            Menu
    1. Imposta gioco.
    2. Gioca
    3. Termina gioco
    1
    

    Consider introducing an enum so you constants to switch instead of just numbers.