LearnFrenzy
Sign in Take a free test

C Input / Output · Predict the Output · Question 8

fgets() and strlen: does the newline count? Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following C program when the input is hi⏎?

main.c
#include <stdio.h>
#include <string.h>

int main(void) {
    char buf[10];
    fgets(buf, sizeof buf, stdin);
    printf("%zu [%s]\n", strlen(buf), buf);
    return 0;
}
  • A 3 [hi ] Correct
  • B 2 [hi]
  • C 3 [hi]
  • D 2 [hi ]
Correct Answer: Option A

fgets keeps the newline, so the string is "hi\n" with length 3, and printing it puts the closing bracket on the next line.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links