1

I am new to C and was playing around with a simple menu based program. However, when a user enters in a blank space, a character, or a string, the program goes into an infinite loop.

I believe it is because I declared option as an int. Will I have to declare an optionChar & optionString to take care of the error or how can I validate that the user enters in an integer instead of char or string in C?

#include <stdio.h>

void foo();
void bar();

int main() {
    int option;

    do {
        printf("MENU\n"
            "1. foo();\n"
            "2. bar();\n"
            "3. Quit\n"
            "Enter your option: ");
        scanf_s("%d", &option);
        /*
        if (!scanf_s("%d", &option)) {
            // What should I do here?
        } else {
            continue;
        }
        */
        switch (option) {
        case 1:
            printf("\nCalling foo() -");
            foo();
            break;
        case 2:
            printf("\nCalling bar() -");
            bar();
            break;
        case 3:
            printf("\nQuitting!\n");
            break;
        default:
            printf("\nInvalid option!\n");
        }
    } while (option != 3);

    return 0;
}

void foo() {
    printf("\nfoo() successfully called.\n\n");
    return;
}

void bar() {
    printf("\nfoo() successfully called.\n\n");
    return;
} 
dumdum
  • 15
  • 2
  • Check the return status from `scanf_s()`. When it is zero rather than 1 (or EOF), you've got a problem — the input is not a number. Either arrange to gobble the input up to the next newline (`int c; while ((c = getchar()) != EOF && c != '\n') ;`) or — since you seem to be on Windows because you're using `scanf_s()` — consider [using `fflush(stdin)`](http://stackoverflow.com/questions/2979209/using-fflushstdin) to clear the input, but be aware that it is not portable, unlike the loop. – Jonathan Leffler Feb 04 '16 at 23:34

1 Answers1

0
int n;    /* The user input choice */
do {
     printf("MENU\n"
            "1. foo();\n"
            "2. bar();\n"
            "3. Quit\n"
            "Enter your option: ");
} while (scanf("%d", &n) != 0 && n >= 1 && n <= 3);

This code displays the menu, and then checks the user input. If it is not a number, or if it is not in the range [1, 3], then the program will display the menu again. The program will continue this until the user enters good input.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75