Prerequisites
Let’s Print our Full Name
To print our full name, the program will take input as a string array and print it.
Note : Before we scan and store a string into a string array variable, we should declare the maximum size for that string array variable which is 20 in this case : char name[20]
Output :
Enter your name : Jagdish Narayan Samal
Hii Jagdish
Wait! What happened to the middle name and the last name ?
This behavior is shown because scanf() doesn’t accept whitespace.
While accepting the sequence of input, it gets terminated where the first whitespace character is, with a null character.
What is the solution ?
Well, instead of scanf() we will use fgets().
The fgets() function
Output :
Enter your name : Tatshat Sarangi
Hii Tatshat SarangiDid fgets() work ?
Okay, so it worked!
Wait! wait! wait! Did you notice the blank the after Hii Tatshat Sarangi ?
Reason : The fgets() adds a new line character at the end of the string on it’s own.
So now we need to replace the \n with \0 .
Correct Way to Print Full Name
Note : For now, you don’t have to understand how the \n got replaced by \0.
You will understand this in the following lessons.
Make sure to include the string.h
Output :
Enter your name : Steve Harrington
Hii Steve Harrington
Did fgets() work ?
Oh yes! It did work.
So this is how you can print a string array with whitespaces.
Outro
Hurray! You’ve now completed a good beginner friendly project.
Have any doubt ?
DM me on Instagram
Peace.