how do you accept a multi word input in c language.?

how do you accept a multi word input in c language.?

3 hours ago 2
Nature

To accept a multi-word input in C language, the best approach is to use the fgets() function instead of scanf(). This is because scanf() stops reading input at the first whitespace, so it only captures a single word. In contrast, fgets() reads an entire line including spaces until a newline character or the specified limit is reached.

Using fgets() for multi-word input:

c

#include <stdio.h>

int main() {
    char input[100];  // Define a character array to hold the input

    printf("Enter a multi-word string: ");
    fgets(input, sizeof(input), stdin);  // Read a line of input including spaces

    printf("You entered: %s", input);

    return 0;
}
  • fgets() takes three arguments: the character array to store the input, the maximum number of characters to read, and the input stream (stdin for keyboard input).
  • It safely reads the entire line including spaces, unlike scanf("%s", ...) which stops at the first space

Why not use scanf() for multi-word input?

  • scanf("%s", ...) reads only until the first whitespace (space, tab, newline), so it cannot capture multiple words.
  • A workaround with scanf() is to use the format specifier %[^\n] which reads until a newline, but this is less safe and less common than fgets()

Summary

  • Use scanf() for single-word input.
  • Use fgets() to accept multi-word strings safely.
  • Avoid gets() because it does not prevent buffer overflow and is unsafe.

This method is the standard and safest way to accept multi-word input strings in C

Read Entire Article