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 the console using gets in C Programming language and the differences between the scanf and gets with example. The basic syntax behind the Gets is shown below.

char *gets(char *str)

or we can simply write it as:

gets(<variable name>)

Gets in C Programming Example

The C gets function is 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.

#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 will be assigned to the character array name[50].

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

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

// 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 This Programming

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

You can observe that though we entered Learn This Programming as the text, we are getting the output as Learn. Because the scanf function will consider Learn as one value, This as another, and Programming as the third value. The following screenshot will prove to 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.

// 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 result, you can observe that we are getting the complete text without any missing letters.

Comments are closed.