A line is read with fgets(buf, sizeof buf, stdin). What does buf contain when the whole input line fits in the buffer?
Correct answer
B. The line including its trailing newline character, if one was present in the input
16 views
B. The line including its trailing newline character, if one was present in the input
16 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is B? Ask here and get an explanation.