Nearby lessons

43 of 72

C - 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
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[30];
6 
7 printf("Enter your name: ");
8 scanf("%29s", name);
9 
10 printf("Your name is %s", name);
11 
12 return 0;
13}
Output
Enter your name: Rahul
Your name is Rahul

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
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[30];
6 
7 printf("Enter your full name: ");
8 scanf("%29s", name);
9 
10 printf("Name: %s", name);
11 
12 return 0;
13}
Output
Enter your full name: Rahul Sharma
Name: Rahul

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
CCode Cell
1#include <stdio.h>
2 
3int main()
4{
5 char name[50];
6 
7 printf("Enter your full name: ");
8 fgets(name, sizeof(name), stdin);
9 
10 printf("Your name is %s", name);
11 
12 return 0;
13}
Output
Enter your full name: Rahul Sharma
Your name is Rahul Sharma

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. Use scanf("%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 Questions
Progress: 0 / 3