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:
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
STDINoption. Then pressRun.
#include<stdio.h> // Including header fileint main(){char myString[50]; // creating a character arraygets(myString); // use gets to store inputprintf("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
getscan be overcome by usingfgets.
Free Resources