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 terminate.

How to read the string data from console using gets in C Programming, and the differences between the scanf and gets with example. 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>)

Gets in C Programming Example

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

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

// C gets function example
#include <stdio.h> 

int main()
{
	char name[50];
	
	printf("\n Please Enter your Full Name: \n");
	gets(name);
	
	printf("=============\n");
	printf("%s", name);
	
	return 0;
}
 Please Enter your Full Name: 
Tutorial Gateway
=============
Tutorial Gateway

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

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

Next, we used the C programming 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 are working with string data.

// C gets function & scanf difference example

#include <stdio.h> 

int main()
{
	char name[50];
	
	printf("\n Please Enter your Full Name: \n");
	scanf("%s", name);
	//gets(name);
	
	printf("\n=============\n");
	printf("%s", name);
	
	return 0;
}
 Please Enter your Full Name: 
Learn C Programming

=============
Learn

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 learning as one value, c as another, and programming as third value. The following screenshot will prove you the same

Gets in C Programming 4

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

// C gets function & scanf difference example

#include <stdio.h> 

int main()
{
	char name[50];
	
	printf("\n Please Enter your Full Name: \n");
	//scanf("%s", name);
	gets(name);
	
	printf("\n=============\n");
	printf("%s", name);
	
	return 0;
}
 Please Enter your Full Name: 
Learn C Programming

=============
Learn C Programming

From the above screenshot, you can observe that we are getting the complete text without any missing letters.

Comments are closed.