Why does a space in my scanf statement make a difference? [duplicate]
When I run the code below, it works as expected.
#include <stdio.h>
int main()
{
char c;
scanf("%c",&开发者_高级运维amp;c);
printf("%c\n",c);
scanf(" %c",&c);
printf("%c\n",c);
return 0;
}
If I remove the space in the second scanf
call (scanf("%c",&c);
), program behaves with the undesirable behavior of the second scanf
scanning a '\n'
and outputting the same.
Why does this happen?
That's because when you entered your character for the first scanf call, besides entering the character itself, you also pressed "Enter" (or "Return"). The "Enter" keypress sends a '\n' to standard input which is what is scanned by your second scanf call.
So the second scanf just gets whatever is the next character in your input stream and assigns that to your variable (i.e. if you don't use the space in this scanf statement). So, for example, if you don't use the space in your second scanf and
You do this:
a<enter>
b<enter>
The first scanf assigns "a" and the second scanf assigns "\n".
But when you do this:
ab<enter>
Guess what will happen? The first scanf will assign "a" and the second scanf will assign "b" (and not "\n").
Another solution is to use scanf("%c\n", &c);
for your first scanf statement.
When you want to read a char discarding new line characters and blank spaces, use
scanf("\n%c",&c);
It works like a charm.
Turn your first scan into:scanf("%c\n",&c);
so that it also picks up the return.
精彩评论