Home

getline

getline is a line-oriented input facility used to read an entire line from a stream into a dynamically allocated buffer. In C, getline refers to a POSIX/GNU extension that may not be available on all platforms. In C++, the standard library provides a separate function, std::getline, used to extract a line from a stream into a string.

In C, the POSIX getline function has the prototype ssize_t getline(char **lineptr, size_t *n, FILE *stream). It

In C++, std::getline reads from an input stream into a std::string (or another character sequence) until the

Portability and usage notes: getline is not part of ISO C, so portable C code often uses

reads
from
stream
until
a
newline
or
end-of-file
is
encountered.
The
newline
is
stored
in
the
buffer.
If
*lineptr
is
NULL,
getline
allocates
memory
with
malloc;
otherwise
it
may
realloc
as
needed.
On
return,
*lineptr
points
to
a
null-terminated
buffer,
*n
is
the
buffer
size,
and
the
function
returns
the
number
of
characters
read,
including
the
delimiter.
If
no
characters
are
read
before
EOF
or
an
error
occurs,
it
returns
-1.
The
caller
must
free
*lineptr
when
finished.
newline
delimiter
is
found.
The
newline
is
extracted
but
not
stored
in
the
string.
It
does
not
require
manual
memory
management.
There
are
variants
that
allow
specifying
a
different
delimiter
or
a
different
output
container.
fgets
or
related
functions;
POSIX
environments
provide
it.
In
C++,
std::getline
is
widely
supported
across
standard
library
implementations.
When
using
the
C
version,
include
the
appropriate
headers
and
manage
the
allocated
buffer;
in
C++,
memory
management
is
handled
by
std::string.