在scanf("%c",&YN)
转换说明符之前放置一个空格,%c
就像scanf(" %c",&YN)
吃掉换行符(\n
)
#include <stdio.h>
#include <ctype.h>
int is_correct(void)
{
char YN ;
printf( "Y or N : " ) ;
scanf(" %c",&YN);
YN = toupper( YN );
return YN == 'Y' ? 1 : YN == 'N' ? 0 : is_correct() ;
}
int main()
{
printf("%d",is_correct());
return 0;
}
我已经测试过了。如果您只输入一个字符(不包括\n
),工作正常!
以更有效的方式,您可以这样做;将第一个字符存储到char ch
然后使用循环while((YN = getchar()) != '\n')
来吃掉所有其他字符,包括\n
. 例如:如果您键入ynabcd
,第一个字符y
将存储在ch
as 中,其余字符将被循环 Y
吃掉。while(
int is_correct(void)
{
char YN ;
printf( "Y or N : " ) ;
scanf("%c",&YN);
char ch = toupper( YN );
while((YN = getchar()) != '\n')
;
return ch == 'Y' ? 1 : ch == 'N' ? 0 : is_correct() ;
}