我是 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;
}
最佳答案
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);
此代码显示菜单,然后检查用户输入。如果不是数字,或者不在 [1, 3] 范围内,则程序将再次显示菜单。该程序将继续执行此操作,直到用户输入正确的输入。
关于c - 在 C 中验证输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35213704/