=====getline=====
#include
template< class charT, class Traits >
std::basic_istream< charT, Traits >& getline( std::basic_istream< charT, Traits >& in,
std::basic_string< charT, Traits >& str );
template< class charT, class Traits >
std::basic_istream< charT, Traits >& getline( std::basic_istream< charT, Traits >& in,
std::basic_string< charT, Traits >& str,
charT delim);
Reads characters from ''in'' input stream until delimiting character ('''\n''' or ''delim'') is found and saves them to the given string ''str''. If delimiter is found, it is discarded.
====Parameters====
''in'' - input stream to read from
''str'' - string to store the read characters to
''delim'' - delimiting character
====Return value====
''in''. Errors are signaled through ''in'' state flags.
====Example====
[[/todo]]
The following code reads a line of text from stdin and displays it
to stdout:
string s;
getline( cin, s );
cout << "You entered " << s << endl;
After getting a line of data in a string, you may find that [[io/sstream/|stringstreams]] are
useful in extracting data from that string. For example, the following code
reads numbers from standard input, ignoring any "commented" lines that begin
with double slashes:
// expects either space-delimited numbers or lines that start with
// two forward slashes (//)
string s;
while( getline(cin,s) ) {
if( s.size() >= 2 && s[0] == '/' && s[1] == '/' ) {
cout << " ignoring comment: " << s << endl;
} else {
istringstream ss(s);
double d;
while( ss >> d ) {
cout << " got a number: " << d << endl;
}
}
}
When run with a user supplying input, the above code might produce this output:
// test
ignoring comment: // test
23.3 -1 3.14159
got a number: 23.3
got a number: -1
got a number: 3.14159
// next batch
ignoring comment: // next batch
1 2 3 4 5
got a number: 1
got a number: 2
got a number: 3
got a number: 4
got a number: 5
50
got a number: 50
====See also====
[[/io/basic_istream/getline]]