Difference between scanf("%c", &c) and scanf(" %c", &c) [duplicate]
The difference between scanf("%c", &c1)
and scanf(" %c", &c2)
is that the format without the blank reads the next character, even if it is white space, whereas the one with the blank skips white space (including newlines) and reads the next character that is not white space.
In a scanf()
format, a blank, tab or newline means 'skip white space if there is any to skip'. It does not directly 'clear the input buffer', but it does eat any white space which looks similar to clearing the input buffer (but is quite distinct from that). If you're on Windows, using fflush(stdin)
clears the input buffer (of white space and non-white space characters); on Unix and according to the C standard, fflush(stdin)
is undefined behaviour.
Incidentally, if you typed the integer followed immediately by a carriage return, the output of your program ends with two newlines: the first was in c
and the second in the format string. Thus, you might have seen:
$ ./your_program
123
int=123
char=
$
That is, the scanf()
reads the newline as its input. Consider an alternative input:
$ ./your_program
123xyz
int=123
char=x
$
The integer input stopped when it read the 'x'; the character input therefore reads the 'x'.
Because after you input the number and press ENTER, the new line stays in the buffer and will be processed by the second scanf
.
In short, you saved new line in the variable c
.
However ,if you use
scanf(" %c",&c);
// ^
the space will consume the new line, which makes c
the value you expected.