When working with input in c++ fgets you may come across various functions for reading strings. One such function inherited from C is fgets(), which is commonly used for reading lines of text safely. While C++ provides alternatives like std::getline(), fgets() is still relevant in many scenarios, especially when working with C-style strings and file input.
What is fgets()?
The fgets() function is used to read a line of text from a file or standard input (stdin). It ensures that the input does not exceed a specified buffer size, making it safer than gets() (which has been deprecated due to buffer overflow risks). The function signature is:
cpp
Copy
Edit
char* fgets(char* str, int num, FILE* stream);
str: A pointer to the character array (buffer) where the input will be stored.
num: The maximum number of characters to read, including the null terminator (\0).
stream: The file pointer from which input is read (e.g., stdin for standard input).
Example Usage of fgets() in C++
Here’s a simple example demonstrating how fgets() can be used to read user input safely:
cpp
Copy
Edit
#include <iostream>
#include <cstdio>
int main() {
char buffer[100]; // Define a buffer to store input
std::cout << "Enter a string: ";
if (fgets(buffer, sizeof(buffer), stdin)) {
std::cout << "You entered: " << buffer;
} else {
std::cerr << "Error reading input.\n";
}
return 0;
}
How fgets() Works
Reads up to num-1 characters from the given stream into str.
Stops reading when a newline character (\n) or EOF (End of File) is encountered.
Appends a null terminator (\0) to the end of the string.
Returns the pointer to str if successful, otherwise returns nullptr on failure.
Handling Newline Characters in fgets()
fgets() retains the newline character (\n) if there is enough space in the buffer. If you need to remove it, you can do so manually:
cpp
Copy
Edit
#include <iostream>
#include <cstdio>
#include <cstring>
int main() {
char buffer[100];
std::cout << "Enter a string: ";
if (fgets(buffer, sizeof(buffer), stdin)) {
buffer[strcspn(buffer, "\n")] = '\0'; // Remove newline character
std::cout << "You entered: " << buffer << std::endl;
}
return 0;
}
Comparison: fgets() vs. std::getline()
Feature fgets() std::getline()
Buffer-based Yes No (uses std::string)
Stops at \n Yes Yes
Includes \n Yes No
Safer than gets() Yes Yes
Works with FILE* Yes No
When to Use fgets() in C++
When working with C-style strings (char arrays).
When reading input from a FILE* stream (e.g., file handling).
When compatibility with legacy C code is needed.
For modern C++ applications, prefer std::getline() with std::string, as it is safer and more flexible. However, fgets() remains useful in specific cases, especially in low-level programming or working with existing C codebases.