Read a Multi-Word String from Console in C

To read a multi-word string from the console in C, we use functions like fgets(), or scanf() with appropriate format specifiers. The scanf() function reads input only until the first whitespace, while fgets() reads an entire line, making it the preferred choice for handling multi-word strings.


Examples to Read Multi-Word Strings

1. Using fgets() to Read a Multi-Word String

In this example, we use fgets() to read a full line of input, including spaces, and store it in a character array.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[100];

    // Prompting user for input
    printf("Enter a sentence: ");
    
    // Using fgets to read multi-word string
    fgets(str, sizeof(str), stdin);

    // Printing the input string
    printf("You entered: %s", str);

    return 0;
}

Explanation:

  1. Declare a character array str of size 100 to store the input.
  2. Use printf() to prompt the user to enter a sentence.
  3. Call fgets(str, sizeof(str), stdin) to read the entire input line, including spaces.
  4. The second argument sizeof(str) ensures that input does not exceed buffer size.
  5. The input is then printed using printf().

Output:

Enter a sentence: Hello World, this is C.
You entered: Hello World, this is C.

2. Using scanf() with Format Specifier

In this example, we will use scanf() with the format specifier %[^\n] to read an entire line until a newline character is encountered.

main.c

</>
Copy
#include <stdio.h>

int main() {
    char str[100];

    // Prompting user for input
    printf("Enter a sentence: ");
    
    // Using scanf to read multi-word string
    scanf("%[^\n]", str);

    // Printing the input string
    printf("You entered: %s", str);

    return 0;
}

Explanation:

  1. Declare a character array str of size 100 to store the input.
  2. Use printf() to prompt the user.
  3. Call scanf("%[^\n]", str) to read all characters until a newline is encountered.
  4. The format specifier %[^\n] tells scanf() to read everything except a newline.
  5. Print the input using printf().

Output:

Enter a sentence: Learning C is easy.
You entered: Learning C is easy.

Conclusion

In this tutorial, we explored different ways to read multi-word strings in C:

  1. fgets(): Recommended method as it reads the entire line safely.
  2. scanf("%[^\n]"): Reads input until a newline, but requires careful formatting.