std::getline (3) - Linux Manuals
std::getline: std::getline
NAME
Synopsis
Defined in header <string>
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, (1)
std::basic_string<CharT,Traits,Allocator>& str,
CharT delim );
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, (1) (since C++11)
std::basic_string<CharT,Traits,Allocator>& str,
CharT delim );
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, (2)
std::basic_string<CharT,Traits,Allocator>& str );
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, (2) (since C++11)
std::basic_string<CharT,Traits,Allocator>& str );
getline reads characters from an input stream and places them into a string:
1) Behaves as UnformattedInputFunction, except that input.gcount() is not affected. After constructing and checking the sentry object, performs the following:
1) Calls str.erase()
2) Extracts characters from input and appends them to str until one of the following occurs (checked in the order listed)
a) end-of-file condition on input, in which case, getline sets eofbit.
b) the next available input character is delim, as tested by Traits::eq(c, delim), in which case the delimiter character is extracted from input, but is not appended to str.
c) str.max_size() characters have been stored, in which case getline sets failbit and returns.
3) If no characters were extracted for whatever reason (not even the discarded delimiter), getline sets failbit and returns.
2) Same as getline(input, str, input.widen('\n')), that is, the default delimiter is the endline character.
Parameters
input - the stream to get data from
str - the string to put the data into
delim - the delimiter character
Return value
input
Notes
When used immediately after whitespace-delimited input, e.g. after int n; std::cin >> n;, getline consumes the endline character left on the input stream by operator>>, and returns immediately. A common solution is to ignore all leftover characters on the line of input with cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); before switching to line-oriented input.
Example
The following example demonstrates how to use getline function to read user's input and how to process file line by line.
// Run this code
Possible output:
See also
getline (public member function of std::basic_istream<CharT,Traits>)