Syntax:
#include <string> istream& std::getline( istream& is, string& s, char delimiter = '\n' );
The C++ string header defines the global function getline() to read strings from an I/O stream. The getline() function, which is not part of the string class, reads a line from is and stores it into s. If a character delimiter is specified, then getline() will use delimiter to decide when to stop reading data.
For example, 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 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
Because the getline() function begins reading at the current file position, it can also be used to read the remainder of a line, or any characters up to the specified delimiter.
Related Topics: get, getline, stringstream