What is gets in C?

The gets function is part of the <stdio.h> header file in C.

It is used when input is required from the user. It takes a single parameter as input, i.e., the variable to store data in. The illustration below shows how gets works:

How does gets work

Function gets allows space-separated strings to be entered by the user. It waits until the newline character \n or an end-of-file EOF is reached. The string is then stored in the form of a character array.

Example

The following code snippet shows how gets can be used:

Input your string using the STDIN option. Then press Run.

#include<stdio.h> // Including header file
int main(){
char myString[50]; // creating a character array
gets(myString); // use gets to store input
printf("You entered: %s", myString);
return 0;
}

Enter the input below

Limitation of gets

As we can see from the output above, the code gives a warning. This is because gets does not perform bound-checking. It does not check whether the user input is within the number of bytes specified for storage in the character array. An input larger than the array capacity may lead to a buffer overflow.

This limitation of gets can be overcome by using fgets.

Copyright ©2024 Educative, Inc. All rights reserved