std::getline

From Cppreference

Jump to: navigation, search
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) (C++11 feature)
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) (C++11 feature)

Reads in unformatted data from a stream into a string. Stops once a character equal to the delimiter is found, or the stream is exhausted. The first version uses delim as the delimiter, the second version uses '\n' as the delimiter. The delimiter character is discarded from the stream and not placed in the string.

[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.";
}

Output:

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.