When you say scanf("%d", &...)
to read an integer, it actually skips leading whitespace, then reads an integer.
When you say scanf("%f", &...)
to read a floating-point number, it actually skips leading whitespace, then reads a floating-point number.
When you say scanf("%s", ...)
to read a string, it actually skips leading whitespace, then reads a string.
Are you beginning to see a pattern? Well, don't get your hopes up, because:
When you say scanf("%c", &...)
to read a character, it does not skip leading whitespace. If there's leading whitespace, the first of the whitespace characters is the character that %c
reads.
This strange exception for %c
made perfect sense for the people who first designed scanf
, but it has been confusing the heck out of everyone else ever since.
This is why, if what you actually want to read is a non-whitespace character, you must use the format specifier " %c"
, with a space before the %
. That space matches zero or more whitespace characters, thus skipping any leading whitespace, and ensuring that %c
will try to read a non whitespace character for you.
And since this is all so confusing and counterintuitive and difficult to explain, sometimes you'll see the more simple explanation of "Just use a leading space before %c
always", because all anybody* ever wants to read is a non-whitespace character, anyway.
[* By "anybody" I mean, any beginner writing a beginning C program. Theoretically there might be an expert somewhere who wants to use %c
to read whitespace characters. But experts generally don't use scanf
for anything.]