Asirino
Asirino

Reputation: 21

Leading whitespace when using scanf() with " %c"

I've read around and everyone says to use " %c" when you're scanning in a single character because there may be white space at the beginning of the input stream.

Okay, fair. But does this ONLY work for the very first character in said input stream? What if I'm now scanning a single character in a string of many contiguous characters? (ex: abcdef)

Wouldn't using " %c" as a format specifier now mess that up?

Upvotes: 0

Views: 1501

Answers (1)

Steve Summit
Steve Summit

Reputation: 47925

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.]

Upvotes: 7

Related Questions