Namespaces
Variants
Views
Actions

Difference between revisions of "cpp/string/basic string/getline"

From cppreference.com
< cpp‎ | string‎ | basic string
m (Synopsis: apply same indents as in e.g. erase()
 
(37 intermediate revisions by 19 users not shown)
Line 1: Line 1:
 
{{cpp/title|getline}}
 
{{cpp/title|getline}}
{{cpp/string/sidebar}}
+
{{cpp/string/basic_string/navbar}}
{{ddcl list begin}}
+
{{dcl begin}}
{{ddcl list header | string}}
+
{{dcl header|string}}
{{ddcl list item | num=1 |
+
{{dcl|num=1|1=
 
template< class CharT, class Traits, class Allocator >
 
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input,
+
std::basic_istream<CharT, Traits>&
                                          std::basic_string<CharT,Traits,Allocator>& str
+
    getline( std::basic_istream<CharT, Traits>& input,
                                          CharT delim );
+
            std::basic_string<CharT, Traits, Allocator>& str, CharT delim );
 
}}
 
}}
{{ddcl list item | num=1 | notes={{mark c++11 feature}} |
+
{{dcl|since=c++11|num=2|1=
 
template< class CharT, class Traits, class Allocator >
 
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input,
+
std::basic_istream<CharT, Traits>&
                                          std::basic_string<CharT,Traits,Allocator>& str
+
    getline( std::basic_istream<CharT, Traits>&& input,
                                          CharT delim );
+
            std::basic_string<CharT, Traits, Allocator>& str, CharT delim );
 
}}
 
}}
{{ddcl list item | num=2 |
+
{{dcl|num=3|1=
 
template< class CharT, class Traits, class Allocator >
 
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>& input,
+
std::basic_istream<CharT, Traits>&
                                          std::basic_string<CharT,Traits,Allocator>& str );
+
    getline( std::basic_istream<CharT, Traits>& input,
 +
            std::basic_string<CharT, Traits, Allocator>& str );
 
}}
 
}}
{{ddcl list item | num=2 | notes={{mark c++11 feature}} |
+
{{dcl|since=c++11|num=4|1=
 
template< class CharT, class Traits, class Allocator >
 
template< class CharT, class Traits, class Allocator >
std::basic_istream<CharT,Traits>& getline( std::basic_istream<CharT,Traits>&& input,
+
std::basic_istream<CharT, Traits>&
                                          std::basic_string<CharT,Traits,Allocator>& str );
+
    getline( std::basic_istream<CharT, Traits>&& input,
 +
            std::basic_string<CharT, Traits, Allocator>& str );
 
}}
 
}}
{{ddcl list end}}
+
{{dcl end}}
  
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 {{tt|delim}} as the delimiter, the second version uses {{cpp|'\n'}} as the delimiter. The delimiter character is discarded from the stream and not placed in the string.
+
{{tt|getline}} reads characters from an input stream and places them into a string:
 +
 
 +
@1,2@ Behaves as {{named req|UnformattedInputFunction}}, except that {{c|input.gcount()}} is not affected. After constructing and checking the sentry object, performs the following:
 +
:@1@ Calls {{c|str.erase()}}.
 +
:@2@ Extracts characters from {{c|input}} and appends them to {{c|str}} until one of the following occurs (checked in the order listed)
 +
::@a@ end-of-file condition on {{c|input}}, in which case, {{tt|getline}} sets {{ltt|cpp/io/ios_base/iostate|eofbit}}.
 +
::@b@ the next available input character is {{c|delim}}, as tested by {{c|Traits::eq(c, delim)}}, in which case the delimiter character is extracted from {{c|input}}, but is not appended to {{c|str}}.
 +
::@c@ {{c|str.max_size()}} characters have been stored, in which case {{tt|getline}} sets {{ltt|cpp/io/ios_base/iostate|failbit}} and returns.
 +
:@3@ If no characters were extracted for whatever reason (not even the discarded delimiter), {{tt|getline}} sets {{ltt|cpp/io/ios_base/iostate|failbit}} and returns.
 +
 
 +
@3,4@ Same as {{c|getline(input, str, input.widen('\n'))}}, that is, the default delimiter is the endline character.
  
 
===Parameters===
 
===Parameters===
{{param list begin}}
+
{{par begin}}
{{param list item | input | the stream to get data from}}
+
{{par|input|the stream to get data from}}
{{param list item | str | the string to put the data into}}
+
{{par|str|the string to put the data into}}
{{param list item | delim | the delimiter character}}
+
{{par|delim|the delimiter character}}
{{param list end}}
+
{{par end}}
  
 
===Return value===
 
===Return value===
{{tt|input}}
+
{{c|input}}
 +
 
 +
===Notes===
 +
When consuming whitespace-delimited input (e.g. {{c|int n; std::cin >> n;}}) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with {{tt|getline}} will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:
 +
* An explicit extraneous initial call to {{tt|getline}}.
 +
* Removing consecutive whitespace with {{c|std::cin >> std::ws}}.
 +
* Ignoring all leftover characters on the line of input with {{c|cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');}}.
  
 
===Example===
 
===Example===
{{example cpp
+
{{example
| The following code asks the user for their name, then greets them using that name.
+
|p=true
| code=
+
|The following example demonstrates how to use the {{tt|getline}} function to read user input, and to process a stream line by line, or by parts of a line using the {{c|delim}} parameter.
#include <string>
+
|code=
 
#include <iostream>
 
#include <iostream>
+
#include <sstream>
 +
#include <string>
 +
 
 
int main()
 
int main()
 
{
 
{
 +
    // greet the user
 
     std::string name;
 
     std::string name;
 
     std::cout << "What is your name? ";
 
     std::cout << "What is your name? ";
 
     std::getline(std::cin, name);
 
     std::getline(std::cin, name);
     std::cout << "Hello " << name << ", nice to meet you.";
+
     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\n";
 +
 
 +
    // use separator to read parts of the line
 +
    std::istringstream input2;
 +
    input2.str("a;b;c;d");
 +
    for (std::string line; std::getline(input2, line, ';');)
 +
        std::cout << line << '\n';
 
}
 
}
| output=
+
|p=true
 +
|output=
 
What is your name? John Q. Public
 
What is your name? John Q. Public
 
Hello John Q. Public, nice to meet you.
 
Hello John Q. Public, nice to meet you.
 +
 +
The sum is 28.
 +
 +
a
 +
b
 +
c
 +
d
 
}}
 
}}
 +
 +
===Defect reports===
 +
{{dr list begin}}
 +
{{dr list item|wg=lwg|dr=91|std=C++98|before={{tt|getline}} did not behave as an unformatted input function|after=behaves as an unformatted input function}}
 +
{{dr list end}}
 +
 +
===See also===
 +
{{dsc begin}}
 +
{{dsc inc|cpp/io/basic_istream/dsc getline}}
 +
{{dsc end}}
 +
 +
{{langlinks|de|es|fr|it|ja|pt|ru|zh}}

Latest revision as of 16:35, 12 May 2024

 
 
 
std::basic_string
Member functions
Element access
Iterators
Capacity
Modifiers
Search
Operations
Constants
Non-member functions
I/O
getline
Comparison
(until C++20)(until C++20)(until C++20)(until C++20)(until C++20)(C++20)
Numeric conversions
(C++11)(C++11)(C++11)
(C++11)(C++11)
(C++11)(C++11)(C++11)
(C++11)
(C++11)
Literals
Helper classes
Deduction guides (C++17)

 
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 );
(2) (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 );
(3)
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 );
(4) (since C++11)

getline reads characters from an input stream and places them into a string:

1,2) 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.
3,4) Same as getline(input, str, input.widen('\n')), that is, the default delimiter is the endline character.

Contents

[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] Notes

When consuming whitespace-delimited input (e.g. int n; std::cin >> n;) any whitespace that follows, including a newline character, will be left on the input stream. Then when switching to line-oriented input, the first line retrieved with getline will be just that whitespace. In the likely case that this is unwanted behaviour, possible solutions include:

[edit] Example

The following example demonstrates how to use the getline function to read user input, and to process a stream line by line, or by parts of a line using the delim parameter.

#include <iostream>
#include <sstream>
#include <string>
 
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\n";
 
    // use separator to read parts of the line
    std::istringstream input2;
    input2.str("a;b;c;d");
    for (std::string line; std::getline(input2, line, ';');)
        std::cout << line << '\n';
}

Possible output:

What is your name? John Q. Public
Hello John Q. Public, nice to meet you.
 
The sum is 28.
 
a
b
c
d

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 91 C++98 getline did not behave as an unformatted input function behaves as an unformatted input function

[edit] See also

extracts characters until the given character is found
(public member function of std::basic_istream<CharT,Traits>) [edit]