Syntax:
istream& istream::getline( char* buffer, streamsize num ); istream& istream::getline( char* buffer, streamsize num, char delim );
The getline() function is used with input streams. The version without a char delim argument effectively sets the delimiter to a newline character. getline() reads characters into buffer until either:
If the delim character (newline normally) is not read, the input stream is set to a failure state.
For example, the following code uses the getline function to display the first 99 characters (one character is reserved for null-termination) or one line at a time from a text file – whichever comes first – (until EOF or a line longer than 99 characters is encountered):
ifstream fin("tmp.dat"); int MAX_LENGTH = 100; char line[MAX_LENGTH]; while( fin.getline(line, MAX_LENGTH) ) { cout << "read line: " << line << endl; }
If you'd like to read lines from a file into strings instead of character arrays, consider using the string getline function.
Those using a Microsoft compiler may find that getline reads an extra character, and should consult the documentation on the Microsoft getline bug.
Related Topics: gcount, get, string getline, ignore, read