Nearby lessons
43 of 72C - String Input
Learn how to take string input from the user in C using scanf() and fgets(). Understand the difference between reading one word and reading a full line with simple examples.
Taking String Input Using scanf()
We can use scanf() to take a string from the user.
When using %s, we do not need to write & before the character array name.
Example01
Limitation of scanf()
The scanf("%s", name) statement reads only one word. If the user enters a full name, it reads only the first word.
Example02
Taking a Full Name Using fgets()
We can use fgets() to read a full name or a sentence containing spaces.
It takes three arguments:
- The character array name.
- The maximum number of characters to read.
stdin, which represents keyboard input.
Example03
Difference Between scanf() and fgets()
Both functions can take string input, but they work differently.
scanf("%s", name)reads one word.fgets()can read a full line containing spaces.fgets()allows us to specify the maximum number of characters to read.
For beginner programs that need a full name or sentence, fgets() is a useful choice.
Common Mistakes
- Using
scanf("%s", &name)for a character array. Usescanf("%s", name). - Expecting
scanf("%s", name)to read spaces. - Using an array that is too small for the input.
- Using
gets(). Avoid it because it does not check the array size.
📝 Key Takeaways
- scanf("%s", name) reads one word.
- scanf() stops reading when it finds a space.
- fgets() can read a full line containing spaces.
- Always provide the array size when using fgets().
- Avoid using the unsafe gets() function.
🧠 Test Your Knowledge
3 QuestionsProgress: 0 / 3