In C input/output programming, which standard library function is most appropriate for reading a multi-word string that includes spaces from standard input?

Difficulty: Easy

Correct Answer: gets()

Explanation:


Introduction / Context:
Reading text that contains spaces (for example, full names or sentences) requires care in C. Basic token-oriented input like scanf with the %s specifier stops at whitespace, which truncates multi-word input. Older C textbooks often used gets to read an entire line including spaces. Although gets is now removed from the C standard due to safety issues, understanding why it was historically chosen explains the intended behavior of multi-word input questions and highlights safer modern alternatives.


Given Data / Assumptions:

  • The task is to read a string that can include spaces (multi-word).
  • We are comparing classic C standard I/O functions.
  • We focus on functional suitability for capturing spaces, not security best practices.


Concept / Approach:

  • scanf with %s reads until the first whitespace, so it fails for multi-word input.
  • gets historically read an entire line up to the newline, thus capturing spaces.
  • printf and puts are output functions and cannot read input at all.


Step-by-Step Solution:

Identify requirement: accept spaces → single-token readers like scanf("%s") are unsuitable.Eliminate output-only functions (printf, puts) because they do not read input.Select the remaining function that reads a whole line including spaces → gets (historically).


Verification / Alternative check:

Practical test: entering 'I am here' → scanf("%s") captures 'I' only; gets would have captured the full line.


Why Other Options Are Wrong:

  • printf(): Output only; cannot read.
  • scanf(): With %s, it stops at whitespace; does not capture multi-word strings without complex formats.
  • puts(): Output only; prints a string with a newline.


Common Pitfalls:

  • Using gets in real code is unsafe because it cannot prevent buffer overflows. Prefer fgets(buffer, size, stdin) in modern C.
  • Assuming scanf("%[^\n]") is trivial; while it can read lines, it requires careful width limits to avoid overflow.


Final Answer:

gets()

More Questions from Strings

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion