When working with C++ for input handling, particularly when dealing with strings, many developers turn to std::getline(), but sometimes, fgets cpp from the C standard library is still used, especially in legacy systems or when dealing with C-style strings (char arrays).
What is fgets?
fgets() is a function from the C standard library that reads a line from a file or standard input (stdin). It is safer than gets(), which is now deprecated due to its inability to prevent buffer overflows. The fgets() function ensures that it does not read more characters than can fit into the buffer.
Syntax of fgets:
cpp
Copy
Edit
char* fgets(char* str, int num, FILE* stream);
str: Pointer to the character array (buffer) where the read string will be stored.
num: Maximum number of characters to be read (including the null terminator).
stream: The input stream (typically stdin for console input).
Example Usage in C++
Even though C++ provides std::getline(), fgets() might still be useful in certain situations. Here's a simple example:
cpp
Copy
Edit
#include <cstdio>
#include <iostream>
int main() {
char buffer[100]; // Buffer for input
std::cout << "Enter a string: ";
if (fgets(buffer, sizeof(buffer), stdin)) {
std::cout << "You entered: " << buffer;
} else {
std::cerr << "Error reading input.";
}
return 0;
}
Key Features of fgets():
Prevents Buffer Overflow: Unlike gets(), fgets() ensures that only a specified number of characters are read.
Handles Newline Character (\n): If a newline is encountered before reaching num - 1 characters, it is stored in the buffer. This means you may need to remove it manually.
Null-Terminated Strings: fgets() always null-terminates the string to prevent undefined behavior.
Removing the Newline (\n) from fgets Input
Since fgets() retains the newline character (\n), it may be necessary to remove it:
cpp
Copy
Edit
#include <cstdio>
#include <iostream>
#include <cstring>
int main() {
char buffer[100];
std::cout << "Enter a string: ";
if (fgets(buffer, sizeof(buffer), stdin)) {
// Remove newline if present
buffer[strcspn(buffer, "\n")] = '\0';
std::cout << "You entered: " << buffer << std::endl;
}
return 0;
}
When to Use fgets() Over std::getline()?
When working with C-style strings in legacy systems.
When reading from file streams (FILE*).
When you want precise control over buffer limits.
Conclusion
While std::getline() is more idiomatic in C++, fgets() remains relevant in cases where C compatibility is required. Understanding its nuances ensures safe and efficient string input handling in C++ applications.