Scanf String in C
In this tutorial, we are going to see how to use scanf() string function in C.
You can use the scanf() function to read a string of characters.
The scanf() function reads the sequence of characters until it meets a space.
How to use Scanf in C
In the following program. Even if the name “Alex Douffet” was entered, only “Alex” was stored in the str array.
#include <stdio.h>
int main()
{
char str[50];
printf("Enter your name: ");
scanf("%s", str);
printf("Your name is %s.", str);
return 0;
}
Output:
Enter your name: Alex Douffet Your name is Alex.
How to read a string with spaces?
You can use the fgets() function to read a string with spaces. And, you can use the put() function to display the string.
#include <stdio.h>
int main()
{
char str[50];
printf("Enter your name: ");
// read a string
fgets(str, sizeof(str), stdin);
printf("Your name is: ");
// display the string
puts(str);
return 0;
}
Output:
Enter your name: Alex Douffet Your name is: Alex Douffet
š Boost your productivity ā Try the best web tools now!





