1. Home
  2. Computer Science MCQs
  3. C Programming
  4. A line is read with fgets(buf, sizeof buf, stdin). What…

Added 30 Nov -0001

A line is read with fgets(buf, sizeof buf, stdin). What does buf contain when the whole input line fits in the buffer?

  1. Only the characters before the newline, since the newline stays in the input stream
  2. The line including its trailing newline character, if one was present in the input Correct answer
  3. The line with the newline stripped away, because fgets always truncates at the line terminator
  4. The line with the newline replaced by a NUL plus the previous buffer contents kept

Correct answer

B. The line including its trailing newline character, if one was present in the input

16 views

MCQSEXAM

Explanation

fgets stores every character it reads up to and including the newline, then appends a NUL, so the buffer normally ends with a newline. This contrasts with fscanf("%s") and the removed gets, which stop before whitespace and leave the newline in the stream. Code comparing user input with strcmp usually must strip that newline, and a full buffer without one signals truncation.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is B? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs