Defined in header <string> | ||
---|---|---|
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim ); | (1) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str, CharT delim ); | (1) | (since C++11) |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input, std::basic_string<CharT,Traits,Allocator>& str ); | (2) | |
template< class CharT, class Traits, class Allocator > std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input, std::basic_string<CharT,Traits,Allocator>& str ); | (2) | (since C++11) |
getline
reads characters from an input stream and places them into a string:
UnformattedInputFunction
, except that input.gcount()
is not affected. After constructing and checking the sentry object, performs the following:str.erase()
input
and appends them to str
until one of the following occurs (checked in the order listed)delim
, as tested by Traits::eq(c, delim)
, in which case the delimiter character is extracted from input
, but is not appended to str
.getline
sets failbit
and returns.getline(input, str, input.widen('\n'))
, that is, the default delimiter is the endline character.input | - | the stream to get data from |
str | - | the string to put the data into |
delim | - | the delimiter character |
input
.
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.
The following example demonstrates how to use getline
function to read user's input and how to process file line by line.
#include <string> #include <iostream> #include <sstream> int main() { // greet the user std::string name; std::cout << "What is your name? "; std::getline(std::cin, name); std::cout << "Hello " << name << ", nice to meet you.\n"; // read file line by line std::istringstream input; input.str("1\n2\n3\n4\n5\n6\n7\n"); int sum = 0; for (std::string line; std::getline(input, line); ) { sum += std::stoi(line); } std::cout << "\nThe sum is: " << sum << "\n"; }
Possible output:
extracts characters until the given character is found (public member function of std::basic_istream ) |
© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
http://en.cppreference.com/w/cpp/string/basic_string/getline