C: scanf 输入单个字符并验证 [英] C: scanf input single character and validation
问题描述
我在 C 中验证单字符 scanf 输入时遇到问题,但找不到有效的现有解决方案...
I've encountered a problem when validating a single-char scanf input in C and I cannot find an existing solution that works...
场景是:一个方法正在接受单个字母'char'类型的输入,然后验证这个输入,如果不满足条件,则弹出错误消息并重新输入,否则返回此字符值.
The scenario is: a method is taking a single letter 'char' type input and then validating this input, if the criteria is not met, then pops an error message and re-enter, otherwise return this character value.
我的代码是:
char GetStuff(void)
{
char c;
scanf("%c", &c);
while(c != 'A' || c != 'P')
{
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &dtChar);
}
return c;
}
但是,无论我输入什么输入,我都会收到无限循环的错误消息.我阅读了其他一些帖子,猜测是 %c 说明符在我按下 Enter 键时没有自动摆脱换行符的问题,所以到目前为止我已经尝试过:
however, i got the infinite loop of error message no matter what input I type in. I read some other posts and guess it's the problem that %c specifier does no automatically get rid of the newline when I hit enter, and so far I have tried:
在 %c 之前/之后放置一个空格,例如:
putting a white space before/after %c like:
scanf(" %c", &c);
编写一个单独的方法或包含在这个 GetStuff
方法中来清理换行符,例如:
write a separate method or include in this GetStuff
method to clean the newline like:
void cleanBuffer(){
int n;
while((n = getchar()) != EOF && n != '\n' );
}
有人可以帮我解决这个问题吗?提前致谢.
Can anyone help me with this problem please? Thank you in advance.
推荐答案
#include <stdio.h>
char GetStuff(void) {
char c;
scanf("%c", &c);
getchar();
while ((c != 'A') && (c != 'a') && (c != 'P') && (c != 'p')) {
printf("invalid input, enter again (A for AM or P for PM): ");
scanf ("%c", &c);
getchar();
}
return c;
}
int main(void) {
printf("Calling GetStuff()...\n");
char x = GetStuff();
printf("User entered %c\n", x);
return 0;
}
您使用 while (c != 'A' || c != 'P')
作为循环条件,但这将始终返回 true.您要使用的是 &&和"运算符,而不是 ||或"运算符.
You are using while (c != 'A' || c != 'P')
as your loop conditional, but this will always return true. What you meant to use is the && "and" operator, instead of the || "or" operator.
此外,在 scanf 语句之后调用 getchar()
以捕获换行符.这应该按照您希望的方式工作.
Also, call getchar()
after your scanf statements, to capture the newline. This should work the way you want it to.
这篇关于C: scanf 输入单个字符并验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!