GETS in C Programming

The C gets function is used to scan or read a line of text from a standard input (stdin) device, and store it in the String variable. When it reads the newline character then the C gets function will be terminated.

In this article we will show you, How to read the string data from console using gets in C Programming, and the differences between the scanf and gets with example.

Syntax of GETS in C Programming

The basic syntax behind the Gets in C Programming language is as shown below.

char *gets(char *str)

or we can simply write it as:

gets(<variable name>)

TIP: You have to include the #include<stdio.h> header before using this Gets function.

Gets in C Programming Example

The gets method is used to read complete set of characters from the console. This program will help you to practically understand this gets function.

First printf statement will ask the user to enter any name or string, and the user specified string will be assigned to character array name[50].

printf("\n Please Enter your Full Name: \n");
gets(name);

Next, we used the printf statements to print the output.

printf("%s", name);

Difference between scanf and gets in C Programming

This program will help you to understand, the differences between the scanf statement and the gets function in c programming. And why we generally prefer gets over scanf, while we working with string data.

From the above screenshot you can observe that, thought we entered Learn C Programming as the text we are getting the output as Learn. Because, scanf function will consider learn as one value, c as another, and programming as third value. Following screenshot will prove you the same

Let me comment the scanf(“%s”, name); statement and use gets function to read text from the console.