这是我从 youtube 教程修改的源代码。该计划的目的是:
它问你的年龄。如果你输入 18 或更多,它会询问你的性别而不是打印你可以输入 dude 或 m'lady(取决于你的性别)。如果你的年龄小于 18 岁,它会打印出“Nothing to see here!”
我想确保如果输入不完全符合我的要求(只有数字或只有字符),它会显示“无效输入”。在我的程序中,程序要求年龄的第一部分,当年龄的输入是字母或符号时,它显示无效输入。但是每当我将字母表与 18a 或 18/之类的数字组合时,它就会显示:
“请输入您的性别。(男/女)” “输入无效。”
此外,如果我输入 18 或更多,然后转到程序询问性别(男/女)的部分,如果我输入数字或符号,它会显示无效输入。但是当我像 m1 或 m/这样组合时,它会显示:
“伙计,你可以进入这个网站。”
谁能帮我解决这个问题?
#include <stdio.h>
#include <conio.h>
int main(void) {
char gender;
int age=0;
printf("Please enter your age. \n");
if(scanf(" %d",&age)!=1) {
printf("invalid input. \n");
return 0;
}
if(age>=18) {
printf("Please enter your gender.(m/f) \n");
if(scanf(" %s", &gender) !=1) {
printf("Invalid input.\n");
return 0;
}
else if(gender== 'm') {
printf("You may enter this website dude.\n");
}
else if(gender== 'f') {
printf("You may enter this website m'lady.\n");
}
else {
printf("Invalid input. \n");
return 0;
}
}
else if(age<18) {
printf("Nothing to see here! \n\n");
return 0;
}
return 0;
}
最佳答案
如果你想避免这种行为,你应该阅读每个用户选项的整行并完全验证它。
要阅读整行,您可以使用 scanf(" %[^\n]",str)
(*) 而不是使用 %d
或 %s
.然后您可以验证用户输入以检查它是否正是您想要的。
额外:
要验证年龄,您可以使用:strtol
正如解释的那样 here , 为了验证性别,我认为简单的字符串比较就可以解决问题。
(*) 在 C 语言中有几个选项可以读取整行(例如 fgets),也有不使用 scanf(" %[^\n]",str)
的原因。 (可能的缓冲区溢出)但我试图向您展示一个使用您正在使用的函数的解决方案,有关此主题的精彩讨论请查看 this post .
关于c - 如何防止非数字或非字符输入或符号并在 C 中获得所需的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34625725/