C Programming for Beginners : scanf() vs fgets()

Suraj Das
2 min readOct 30, 2021

--

Photo by Brands&People on Unsplash

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 Sarangi
Did 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.

Index of C Programming lessons :

  1. Getting Started within 5 minutes
  2. Learning Fundamentals Made Easy
  3. Circumference and Area of Circle
  4. scanf() vs fgets()
  5. Hypotenuse Calculator
  6. Learn by Building a Calculator
  7. Functions
  8. More on Functions
  9. Length of an Array
  10. String Functions
  11. The While Loop

--

--