1
我是C新手,正在玩一個簡單的基於菜單的程序。但是,當用戶輸入空格,字符或字符串時,程序會進入無限循環。驗證在C輸入
我認爲這是因爲我宣佈選項爲int
。我將不得不聲明一個optionChar
& optionString
來照顧錯誤或我如何驗證用戶輸入一個整數而不是字符或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;
}
檢查'scanf_s()'的返回狀態。當它是零而不是1(或EOF)時,您遇到了問題 - 輸入不是數字。或者安排把輸入放到下一個換行符('int c; while((c = getchar())!= EOF && c!='\ n');')或者 - 因爲你似乎在Windows上,因爲你正在使用'scanf_s()' - 考慮[使用'fflush(stdin)'](http://stackoverflow.com/questions/2979209/using-fflushstdin)清除輸入,但要注意它不是可移植的,不像循環。 –