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;
}