ProgrammingHardProduct company OA

The user types hello and presses Enter. After `char buf[8]; fgets(buf, sizeof buf, stdin);`, what does buf hold?

  1. A. Only "hel", because fgets reads sizeof buf / 2 characters
  2. B. "hello": the newline is discarded
  3. C. "hello\n": the newline is kept, followed by '\0'
  4. D. "hello\n" with no terminating '\0'

Correct answer: C. "hello\n": the newline is kept, followed by '\0'

fgets reads up to sizeof buf − 1 characters, stopping after a newline, which it stores, and always adds '\0'. That kept '\n' is why code often strips it with buf[strcspn(buf, "\n")] = '\0'.

More C Programming questions

Exams that ask this topic