ProgrammingHardProduct company OA

After `scanf("%d", &n);` reads the input 42 followed by Enter, why does the next getchar() return '\n' instead of waiting for new input?

  1. A. %d stores the newline in n along with 42
  2. B. scanf always appends a newline to its input
  3. C. getchar reads from a different stream than scanf
  4. D. %d stops at the newline and leaves it unread in the input buffer

Correct answer: D. %d stops at the newline and leaves it unread in the input buffer

Conversions like %d skip leading white space but stop at the first character that cannot be part of the number, leaving it unread. The leftover '\n' is the next character available. A space in the format (" %c") or a loop that discards up to '\n' fixes it.

More C Programming questions

Exams that ask this topic