#include <fstream>
  istream& getline( char* buffer, streamsize num );
  istream& getline( char* buffer, streamsize num, char delim );

The getline() function is used with input streams, and reads characters into buffer until either:

  • num - 1 characters have been read,
  • a newline is encountered,
  • an EOF is encountered,
  • or, optionally, until the character delim is read. The delim character is not put into buffer.

For example, the following code uses the getline function to display the first 100 characters from each line of a text file:

  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.