LearnFrenzy
Sign in Take a free test

Strings · Find the Error · Question 4

Bug: scanf("%s") reads only the first word Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The user types Asha Rao and presses Enter. What does the program print, and why?

main.c
#include <stdio.h>

int main(void) {
    char name[32];
    if (scanf("%31s", name) != 1)
        return 1;
    printf("Hello, %s!\n", name);
    return 0;
}
  • A Hello, Asha Rao!
  • B Hello, Asha! – %s stops reading at the first whitespace Correct
  • C Hello, ! – %s skips letters
  • D It overflows name
Correct Answer: Option B

%s reads a single word: it skips leading whitespace and stops at the next space. The 31 width is good practice (it prevents overflow). To read a full line, use fgets().

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