The gets()
function in C++ is a standard library function housed within the <cstdio>
header, primarily used for reading strings from standard input (stdin). It captures an entire line from stdin, up to but not including the newline character, and stores it into a buffer provided by the user. Despite its utility, gets()
has been deprecated due to safety concerns, primarily buffer overflow vulnerabilities.
In this article, you will learn how to use the gets()
function to read input strings from the user. Explore how gets()
operates, its associated risks, and alternatives that can be used to achieve similar functionality safely.
gets()
gets()
Include the <cstdio>
header in your C++ program.
Declare a buffer to store the input string.
Use the gets()
function to read the input from stdin.
#include <cstdio>
int main() {
char str[100];
printf("Enter a string: ");
gets(str);
printf("You entered: %s\n", str);
return 0;
}
This code snippet sets up a buffer str
capable of holding up to 99 characters (allowing space for the null terminator). The gets()
function reads a line of text from the user and stores it in this buffer.
gets()
Realize that gets()
does not perform bounds checking.
Recognize the risk of buffer overflow, which can lead to security vulnerabilities.
When using gets()
, if the input exceeds the buffer size, it can overwrite adjacent memory areas, causing crashes or exploited vulnerabilities.
gets()
fgets()
for Safer InputUse fgets()
for reading lines safely with buffer size limitation.
Specify the buffer, the maximum size, and the stdin stream as arguments to fgets()
.
#include <cstdio>
int main() {
char str[100];
printf("Enter a string: ");
fgets(str, sizeof(str), stdin);
printf("You entered: %s", str); // `fgets()` includes the newline character in the buffer
return 0;
}
Here, fgets()
reads up to 99 characters and includes safety for preventing buffer overflow. Note that fgets()
keeps the newline character if it reads it before reaching the buffer limit.
Utilize C++ std::string
and std::getline()
for dynamic input handling.
Include the <iostream>
and <string>
headers for this purpose.
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "Enter a string: ";
std::getline(std::cin, input);
std::cout << "You entered: " << input << std::endl;
return 0;
}
This approach uses C++ standard library features, providing more flexibility and safety compared to gets()
.
While the gets()
function in C++ offers a straightforward method to read strings from stdin, its usage is strongly discouraged due to the inherent risks of buffer overflow. Explore and utilize safer alternatives like fgets()
and C++ strings with std::getline()
for robust and secure input handling in your applications. By adhering to these safer practices, you ensure that your applications remain robust, secure, and maintainable.