4

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
n0nChun
  • 720
  • 2
  • 8
  • 21
  • 1
    search for and read up on scanf and format characters - that said, the space is eating your carriage return from the first input, that's why you have the results you do. – KevinDTimm Aug 23 '11 at 19:09

3 Answers3

4

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

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

It works like a charm.

ib.
  • 27,830
  • 11
  • 80
  • 100
4

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.

Chaitanya Gupta
  • 4,043
  • 2
  • 31
  • 41
0

Turn your first scan into:scanf("%c\n",&c); so that it also picks up the return.

Marius Burz
  • 4,555
  • 2
  • 18
  • 28
  • 1
    The `\n` will also pick up any other white-space characters. Any white-space in the format string (including `'\n'`) tells `scanf` to read zero or more white-space characters. – Keith Thompson Aug 23 '11 at 19:23
  • 1
    @Keith Exactly that's what his second scanf is doing, it's "ignoring" all whitespaces and reads the first not-whitespace char in c. My choice for \n upon " " was deliberated because it is easier to comprehend what it is doing. – Marius Burz Aug 23 '11 at 19:32
  • `\n` after `%c` actually reads the `\n`. it waits for input, but captures the newline. – 101is5 Oct 11 '22 at 18:38