Difference between scanf ("% c", & c) and scanf ("% c", & c)
Consider the following C code snippet:
#include <stdio.h> int main() { int a; char c; scanf("%d",&a); scanf("%c",&c); printf("int=%d\n",a); printf("char=%c\n",c); } I can enter only an integer, not a character. The output is just an integer value, and no value is output for the second printf statement.
However, if I use a space before the format specifier:
scanf(" %c",&c); It works as expected. Why is this so?
Someone told me that this is related to flushing the input buffer. Can someone shed light on the same thing?
The difference between scanf("%c", &c1) and scanf(" %c", &c2) is that the format reads the next character without a space, even if it is a space, while the one with a space runs through a space (including characters new line), and reads the next character is not empty space.
In scanf() format, empty, tab or new line means "skip empty space if there is something to skip." It does not directly "flush the input buffer", but it is any white space that is similar to flushing the input buffer (but completely different from this). If you are running Windows, fflush(stdin) clears the input buffer (spaces and non-white spaces); on Unix and according to the C standard, fflush(stdin) is undefined behavior.
By the way, if you typed an integer followed immediately by a carriage return, the output of your program ends with two new lines: the first was in c , and the second in the format line. So you could see:
$ ./your_program 123 int=123 char= $ That is, scanf() reads the new line as input. Consider an alternative input:
$ ./your_program 123xyz int=123 char=x $ The whole input is stopped when it reads "x"; therefore character input reads "x".
You need to pass a pointer to the data object specified in the format string, therefore
scanf("%c", c); will actually pass the value of c, which in turn can cause a program error,
scanf("%c", &c); will pass the address c, allowing scanf to change the value of your copy.
The space after% c will make it look for a character, and then a space. If there is no space, it will not read the character