std::getline
From cppreference.com
< cpp | string | basic string
Defined in header <string>
|
||
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(1) | |
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(1) | (since C++11) |
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, |
(2) | |
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, |
(2) | (since C++11) |
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)
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
.
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.
[edit] Parameters
input | - | the stream to get data from |
str | - | the string to put the data into |
delim | - | the delimiter character |
[edit] Return value
input
[edit] Example
The following code asks the user for their name, then greets them using that name.
#include <string> #include <iostream> int main() { std::string name; std::cout << "What is your name? "; std::getline(std::cin, name); std::cout << "Hello " << name << ", nice to meet you."; }
Possible output:
What is your name? John Q. Public Hello John Q. Public, nice to meet you.