Skip to main content

Command Palette

Search for a command to run...

fgets vs getline: Which Function to Use and Why

Published
2 min read

Both methods are used to take input in C++, and we can use either one. But why do we need a distinction between these two methods?

The reason is that when we use fgets, we can see how memory is allocated. To understand this more clearly, let's look at the syntax of fgets.

fgets(char *str, int count, FILE* stream)

Now, what does this mean?

str indicates where we will store our memory, like a variable. count specifies how much space we need to allocate for the memory. stream tells us where we are reading the memory from. For example, if we are writing a program and want to type in the input, we can use stdin here.

Here is a simple code example to see fgets in action. This is a basic C-style safe code for fgets.

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
  char data[20];
  int count = 20;
  if (fgets(data, count, stdin)) {
    cout << data << "\n";
  }
  return 0;
}

For this code, we can get the output like this:

 ./build/main                                                                                                                                                                            ─╯
hello
hello

Now, a better alternative that helps us avoid dealing with memory allocation is the getline() function in C++.

Here is a very simple code example to see getline in action:

#include <iostream>
using namespace std;

int main(int argc, char *argv[]) {
  string s;
  getline(cin, s);
  cout << "The value taken as an input using getline() is: " << s << "\n";
  return 0;
}

The output for this code would look like this:

./build/main                                                                                                                                                                            ─╯
hello world why am i learning cpp
The value taken as an input using getline() is: hello world why am i learning cpp

Here, the main difference between using getline instead of fgets is that we have less hassle with memory management because getline() handles it for us. In modern C++ systems, using getline is standard, but in legacy systems, you might still find fgets.

This completes a very basic understanding of fgets vs. getline().