好吧,我知道有很多问题scanf,但我仍然想问.我希望有人可以解释这个问题的规则或原则:
代码优先:
#include <stdio.h>
int main()
{
int c = 'W';
while(c != 'F'){
scanf("%c",&c);
printf("c is : %c\n",c);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是输出:
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
Run Code Online (Sandbox Code Playgroud)
好吧,我现在还能理解,因为我输入的换行符每次在字母表后按下缓冲区和赋值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;
}
Run Code Online (Sandbox Code Playgroud)
然后我得到这个屏幕:
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
Run Code Online (Sandbox Code Playgroud)
我也有尝试刷新stdin和stdout,还是没有用.
注意:我知道如果使用scanf("%c",c);和另一个scanf("%c",&d);后面处理'\n'可以解决这个问题,我只是认为,我希望了解为什么code2的问题发生了.
我之前已经检查了答案,但我不是一个非常小心的人,如果这个答案真的重复,所有downvote都可以理解.:)
提前致谢.
将连续的空白区域的任意组合传递给scanf(包括空格,制表符和换行符,无论如何)意味着"读取直到发生第一个非空格"(包括EOF).
在你的第二个例子中,scanf读取'E',读取换行符并仍然等待出现非空格.