0
votes

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?

1
You are a new contributor and welcome, but this not how you ask a question. You should work on your code and put what have you done so far, here. Read the Help Center topics to learn more about what questions you can ask and what type of questions you have to avoid. Help Center, What types of questions should I avoid asking?, What topics can I ask about here?. Community will definitely be glad to help you for right questions.Armin Taghavizad
The space character in " %c" matches zero or more whitespace characters. The key word there is "zero". So it will work just fine with your example.user3386109
It's not so much that there may be "whitespace at the beginning of the input stream" but whitespace remaining in the input buffer after scanning a previous input (a newline for example). Although the filter doesn't care why its there, it just filters it.Weather Vane
@Armin is there anywhere I can just ask general questions like this?Asirino

1 Answers

4
votes

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