Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a space in my scanf statement make a difference? [duplicate]

Tags:

c

scanf

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 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?

like image 577
n0nChun Avatar asked Feb 24 '23 05:02

n0nChun


2 Answers

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.

like image 90
Chaitanya Gupta Avatar answered Feb 25 '23 19:02

Chaitanya Gupta


When you want to read a char discarding new line characters and blank spaces, use

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

It works like a charm.

like image 33
Manel Guerrero Zapata Avatar answered Feb 25 '23 18:02

Manel Guerrero Zapata