Why does the space in my scanf command matter?

When I run the code below, it works as expected.

#include <stdio.h> int main() { char c; scanf("%c",&c); printf("%c\n",c); scanf(" %c",&c); printf("%c\n",c); return 0; } 

If I remove the space in the second call to scanf ( scanf("%c",&c); ), the program behaves with the undesirable behavior of the second scan scanf a '\n' and displays it.

Why is this happening?

+4
source share
3 answers

This is because when you entered your character for the first call to scanf, in addition to entering the character itself, you also pressed "Enter" (or "Return"). The "Enter" key sends the standard data input '\ n', which is checked by your second call to scanf.

That way, the second scanf just gets everything that is the next character in your input stream and assigns it to your variable (i.e. if you don't use a space in this scanf statement). So, for example, if you are not using space in the second scanf and

You do it:

 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" (not "\ n").

Another solution is to use scanf("%c\n", &c); for your first scanf statement.

+3
source

If you want to read char discarding newlines and spaces, use

 scanf("\n%c",&c); 

It works like a charm.

+4
source

Turn your first scan to: scanf("%c\n",&c); so that it also returns a result.

0
source

All Articles