The C library gets() function is used to read a line from the standard input stream (stdin) and store it into the string pointed to by str. It continues reading characters from the input stream until a newline character is encountered or the end-of-file is reached. The newline character is then replaced by a null terminator, and the resulting string is stored in str.
SyntaxFollowing is the C library syntax of the gets() function −
char *gets(char *str);Parameters
This function takes only a single parameter −
The gets() function returns the same pointer str on success. On failure or end-of-file condition, it returns NULL.
Example 1: Reading a String from Standard InputThis example reads a string from the standard input using gets() and then prints the entered string.
Below is the illustration of C library gets() function.
#include <stdio.h> int main() { char str[100]; printf("Enter a string: "); gets(str); printf("You entered: %s\n", str); return 0; }Output
The above code produces following result−
Enter a string: Hello, World! You entered: Hello, World!Example 2: Handling Buffer Overflow
This example shows what happens when the input string exceeds the size of the buffer, causing a buffer overflow. Only the first few characters that fit into the buffer are stored, leading to unexpected behavior.
#include <stdio.h> int main() { char str[5]; printf("Enter a string: "); gets(str); printf("You entered: %s\n", str); return 0; }Output
After execution of above code, we get the following result
Enter a string: Overflow You entered: Over
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4