How to validate input when a user has to choose a number between 1 and 3 in C

1 Answer

0 votes
#include <stdio.h>

int main()
{
    int number;

    while (1) {
        printf("Choose 1, 2 or 3: ");

        if (scanf("%d", &number) != 1) {
            while ((number = getchar()) != '\n' && number != EOF) {} // fflush(stdin);
        }

        if (number == 1 || number == 2 || number == 3) {
            break;
        }

        puts("Invalid selection, choose again.");
    }

    printf("You choose: %d\n", number);
}



/*
run:

Choose 1, 2 or 3: 6
Invalid selection, choose again.
Choose 1, 2 or 3: a
Invalid selection, choose again.
Choose 1, 2 or 3: 2
You choose: 2

*/

 



answered Aug 8, 2024 by avibootz

Related questions

1 answer 345 views
1 answer 148 views
1 answer 278 views
278 views asked Oct 6, 2015 by avibootz
2 answers 195 views
195 views asked Jun 2, 2023 by avibootz
...