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:
- Declare a character array
str
of size 100 to store the input. - Use
printf()
to prompt the user to enter a sentence. - Call
fgets(str, sizeof(str), stdin)
to read the entire input line, including spaces. - The second argument
sizeof(str)
ensures that input does not exceed buffer size. - 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:
- Declare a character array
str
of size 100 to store the input. - Use
printf()
to prompt the user. - Call
scanf("%[^\n]", str)
to read all characters until a newline is encountered. - The format specifier
%[^\n]
tellsscanf()
to read everything except a newline. - 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:
fgets()
: Recommended method as it reads the entire line safely.scanf("%[^\n]")
: Reads input until a newline, but requires careful formatting.