Programming Fundamentals · Interview question

You read a number with %d and then read a character with %c, but the %c doesn't wait for input. Why?

A strong answer

%d consumes only the digits it needs and stops at the first non-digit. When the user presses Enter, the newline character (\n) stays in the input buffer. The next scanf("%c", &letter) reads exactly one byte from that buffer, which is the leftover \n, not a fresh character from the user. The fix is to write scanf(" %c", &letter) with a leading space in the format string. That space tells scanf to skip any amount of whitespace, including the leftover newline, before reading the character.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Input & Output

How a program talks to the outside world. printf and scanf in C: format specifiers, common traps, and why the return value matters.

More Input & Output questions

Browse all 472 interview questions
You read a number with %d and then read a character with %c, but the %c doesn't wait for input. Why? | EmbeddedPrep.io