Search code examples
cvalidationgoto

Validating Input goes into infinite loop


I am trying to validate the input if it is something else other than 1 to 3 it will prompt invalid input and also try to get a new input until it is valid.

This piece of code is working well when I'm trying to enter any number out of 1 to 3 but once I input alphabet the code goes into infinite loop.

    int searchBy;

searchInput:
    printf("1 - Search by id\n");
    printf("2 - Search by name\n");
    printf("3 - Search by marks\n>> ");
    printf("Please choose the searching method\n>> ");
    scanf("%d", &searchBy);
    if(searchBy >= 1 && searchBy <= 3){
        printf("Success");
    }
    else{
        printf("\nInvalid input please try again...\n\n");
        goto searchInput;
    }

I tried using while loop but it still goes into infinite loop when I am trying to input alpahbets. It seems like the program doesn't freeze at scanf but keep looping

while(searchBy >= 1 && searchBy <= 3 != 1){
        printf("\nInvalid input please try again...\n\n");
        printf("1 - Search by id\n");
        printf("2 - Search by name\n");
        printf("3 - Search by marks\n>> ");
        printf("Please choose the searching method\n>> ");
        scanf("%d", &searchBy);
    }

Solution

  • You will need to consume the character not accepted by scanf..... One solution is to use getchar() after the 'scanf'.

    scanf("%d", &searchBy);
    getchar();//consume the character not accepted by scanf
    if(searchBy >= 1 && searchBy <= 3){
        printf("Success");
    }
    else{
        printf("\nInvalid input please try again...\n\n");
        goto searchInput;
    }