ProgrammingVery hardProduct company OA

The user types abcdefghij and presses Enter. What is strlen(buf) after `char buf[8]; fgets(buf, sizeof buf, stdin);`?

  1. A. 7
  2. B. 8
  3. C. 10
  4. D. 11

Correct answer: A. 7

fgets stores at most n − 1 = 7 characters and then the '\0', so buf holds "abcdefg". The rest of the line, including the newline, stays in the input for the next read. It never overflows the buffer, unlike gets.

More C Programming questions

Exams that ask this topic