【发布时间】:2013-08-10 23:23:00
【问题描述】:
嗯,我知道有很多关于scanf 的问题,但我还是想问。希望有人能解释一下这个问题的规则或原则:
代码优先:
#include <stdio.h>
int main()
{
int c = 'W';
while(c != 'F'){
scanf("%c",&c);
printf("c is : %c\n",c);
}
return 0;
}
这是输出:
E
c is : E
c is : <--newline
G
c is : G
c is : <---newline again
W
c is : W
c is : <---newline
F
c is : F
好吧,我现在仍然可以理解,对于我输入的换行符,每次按字母后都会留在缓冲区和赋值 c。所以,我尝试 code2:
#include <stdio.h>
int main()
{
int c = 'W';
while(c != 'F'){
scanf("%c\n",&c); //<-- the only modified place.
printf("c is : %c\n",c);
}
return 0;
}
然后我得到这个屏幕:
E
G <---why the input and has one step before the output?
c is : E
W
c is : G
S
c is : W
C
c is : S
F
c is : C
R <---R was left in stdin, turn to a garbage, I didn't hope this.
c is : F
我也试过刷stdin和stdout,还是没用。
注意:我知道如果使用scanf("%c",c);和另一个scanf("%c",&d);后面处理'\n'可以解决这个问题,我只是困惑,我希望明白为什么code2的问题发生了。
我之前已经检查过答案,但我不是一个很细心的人,如果这个答案真的重复,所有的反对意见都可以理解。 :)
提前致谢。
【问题讨论】:
-
您最好只使用
scanf("%c ",&c),它会跳过所有尾随空格。 -
当在
scanf()的格式末尾使用\n时,是时候考虑fgets()和scanf()了。