What does space in scanf mean? [duplicate]
#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?
Solution 1:
White space (such as blanks, tabs, or newlines) in the format string match any amount of white space, including none, in the input.
http://www.manpagez.com/man/3/scanf/
Solution 2:
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. However, when you are using a format specifier that does not ignore whitespace, including space into the format when necessary (to force the skip) might make sense.
The specifiers that do not ignore whitespace are c
[
and n
. So, specifying a space in front of one of those specifiers makes a difference. Otherwise, it doesn't make any difference. In your specific example, the whitespace is ignored specifically because you used a space in your scanf
format (since your are using %c
). Try removing the space and see what happens.
Solution 3:
A whitespace character in the format string will ignore 0 or more whitespace characters from the input, until the first non-whitespace character.
Solution 4:
The documentation for scanf says:
A directive composed of one or more white-space characters shall be executed by reading input until no more valid input can be read, or up to the first byte which is not a white-space character, which remains unread.
And also
Input white-space characters (as specified by isspace ) shall be skipped, unless the conversion specification includes a [ , c , C , or n conversion specifier.
Which means the space in your format string is needed. If you were going to read an integer, however, the space would have been redundant:
/* equivalent statements */
scanf(" %d %d %d", &v1, &v2, &v3);
scanf("%d%d%d", &v1, &v2, &v3);
Solution 5:
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.