Home

stdgetlinestdcin

std::getline and std::cin are central to reading lines in C++. The function std::getline reads characters from an input stream into a string until a delimiter is encountered, defaulting to the newline character. It is defined in the standard library and is commonly used with std::string, but there are overloads for other character types, such as std::wstring with std::wcin.

The typical form is std::getline(std::istream& is, std::string& s); a second form allows a custom delimiter: std::getline(std::istream&

Usage examples are straightforward: std::string line; std::getline(std::cin, line); reads a line from standard input into line.

Common pitfalls include mixing operator>> and std::getline, which can leave a newline in the buffer and cause

Overall, std::getline provides a safe, convenient way to read whole lines from streams into strings, with flexible

is,
std::string&
s,
char
delim);
There
are
analogous
overloads
for
wide
strings
when
using
std::wcin
and
std::wstring.
The
function
reads
characters
from
is,
appends
them
to
s,
and
stops
when
the
delimiter
is
found
or
end-of-file
is
reached.
The
delimiter
is
extracted
from
the
stream
but
not
stored
in
s.
The
function
returns
the
stream,
enabling
expression
chaining.
With
a
different
delimiter:
std::getline(std::cin,
line,
';');
reads
up
to
the
first
semicolon.
If
the
end
of
file
is
reached
before
any
characters
are
extracted,
the
stream
enters
an
EOF
state;
if
characters
were
read,
they
are
stored
in
the
string
and
the
function
may
set
eofbit.
an
empty
line
to
be
read.
A
typical
fix
is
to
clear
the
input
buffer
first,
for
example
using
std::cin.ignore(std::numeric_limits<std::streamsize>::max(),
'\n')
before
calling
getline.
delimiter
support
and
consistent
behavior
across
char
and
wchar_t
variants.