我正在编写一个程序,允许用户输入字母数字字符串并根据可用选项验证他们的输入。当我运行下面的代码时,它总是打印选项无效,即使我输入了范围内的选项。谁能帮我解决这个问题?我们将不胜感激。
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main (void){
char option;
do{
printf("\n\n----------------------------------------------------\n");
printf("Main Menu\n");
printf("----------------------------------------------------\n");
printf("1. Add Record\n");
printf("2. Delete record\n");
printf("3. List Record\n");
printf("4. Exit\n");
printf("----------------------------------------------------\n");
printf("Enter your option:");
scanf("%c",&option);
if(isdigit(option)){
switch(option){
case 1:
add();
break;
case 2:
del();
break;
case 3:
listrec();
break;
case 4:
return 0;
default:
printf("The number that you have entered is invalid.Please enter a new option\n");
break;
}
else{
printf("The option that you have entered is invalid.Please enter a new option\n");
}
}while(option!=4);
return 0;
}
最佳答案
除了使用 1
而不是 '1'
(你需要将字符与字符进行比较,而不是与数字进行比较),还有另一个问题 - 你不' t 从输入中获取回车,这使得输入在第二次通过时失败。请参阅下面的可能解决方案:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
int main (void){
char option;
do {
printf("\n\n----------------------------------------------------\n");
printf("Main Menu\n");
printf("----------------------------------------------------\n");
printf("1. Add Record\n");
printf("2. Delete record\n");
printf("3. List Record\n");
printf("4. Exit\n");
printf("----------------------------------------------------\n");
printf("Enter your option:");
if(scanf("%c",&option)==1) {
if(isdigit(option)){
printf("you entered %c\n", option);
switch(option){
case '1':
printf("adding\n");
break;
case '2':
printf("deleting\n");
break;
case '3':
printf("listing\n");
break;
case '4':
return 0;
default:
printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
break;
}
}
else {
printf("you entered not a digit: %c\n", option);
printf("The number that you have entered is invalid.\nPlease enter a new option:\n");
}
// empty the input buffer:
while(getchar()!='\n');
}
}
} while(option!=4);
return 0;
}
一些注意事项:
- 您的代码示例中缺少一个
- 在
switch
的末尾和else
之间
- 我检查
scanf
返回值1
(有效转换)- 根据 Nisse 的评论 - 我在
if
之后清空输入缓冲区,直到我得到一个EOL
(它在scanf
之后保留在缓冲区中)。这确保读取的下一个字符是回车后的下一个字符,而不是回车本身。 - 杂项清理...
关于c 程序.数据验证。将字符转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24406720/