scanf("%c") 自动读取 10 [英] scanf("%c") automatically reads 10
问题描述
void main()
{
int cnt=1;
char i;
while(cnt<4)
{
printf("\nenter the character");
scanf("%c",&i);
if(i>64 && i<91)
printf("\ncharacter is entered");
else
printf("\nnumber is entered");
cnt++;
}
}
在上面的程序中,在第二次迭代时,i
自动取10,所以控制转到else
部分.谁能帮我找出问题所在?
In the above program, during the second iteration, i
automatically takes 10. So the control goes to else
part. Can anyone help me find what is the issue?
推荐答案
在第一次迭代中,您输入一个字符并按 Enter.scanf
使用您输入的字符,将 \n
留在标准输入流 (stdin
) 中.
In the first iteration, you type a character and press Enter. scanf
consumes the character you entered, leaving the \n
in the standard input stream (stdin
).
在第二次迭代中,scanf
看到 \n
字符消耗了它,因此不需要等待进一步的输入.
In the second iteration, scanf
sees the \n
character consumes it, thus not waiting for further input.
您可以使用以下命令告诉 scanf
读取并丢弃下一个字符:
You can tell scanf
to read and discard the next character by using:
scanf("%c%*c", &i);
或者您可以告诉 scanf
在读取字符并将其存储在 i
之前使用以下命令读取并丢弃所有空白字符(如果有):
or you can tell scanf
to read and discard all whitespace characters, if any, before reading a character and storing it in i
by using:
scanf(" %c",&i);
/* ↑ Note the space */
这篇关于scanf("%c") 自动读取 10的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!