Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c

What is gets in C?

Hassaan Waqar

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

c

CONTRIBUTOR

Hassaan Waqar
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring