#include <stdio.h>
int main(int argc, char* argv[]) {
char c;
scanf(" %c", &c);
printf("%c\n", c);
return 0;
}
[root@test]# ./scanf
a
a
[root@test]# ./scanf
h
h
It seems always matching whether space exists,why?
Space in scanf format means "skip all whitespace" from the current position on. Since most scanf format specifier will already skip all whitespace before attempting to read anything, space is not used in scanf format most of the time.
When you use scanf with %s it reads until it hits whitespace. To read the entire line you may want to consider using fgets().
Space before %c removes any white space (blanks, tabs, or newlines). It means %c without space will read white sapce like new line(\n), spaces(' ') or tabs(\t). By adding space before %c, we are skipping this and reading only the char given.
The value of ch2 is ',' and that is not too surprising either. It is likely that you might expect the value of ch3 to be '1', since that is the next visible character on the input line, but notice that scanf does not skip white space when it is reading character data, as it does when it reads numeric values.
The %c will not skip whitespace char as numeric format specifiers do. So if you use :
#include<stdio.h>
int main(int argc, char* argv[]){
char c;
scanf("%c", &c);
printf("%c\n", c);
scanf("%c", &c); // Try running with and without space
printf("%c\n", c);
return 0;
}
It is very likely that the previous whitespace character in the input buffer will be taken in the second scanf, and you will not get a chance to type. The space before %c will make scanf skip whatever whitespace character is there in the input buffer so that you will be able to enter your input properly. Sometimes to get the same effect people write:
fflush(stdin);
scanf("%c" &c);
But this is considered very bad programming as C Standard specifies the behavior of fflush(stdin) is undefined. So always use space in the format string unless you have a specific reason to capture whitespacesas well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With