Skip to main content

12.6) Reading Lines From A Text File


Entire lines of text can be read from a file like so:

ifstream infile("test.data");
if (not infile.is_open()) {
  cerr << "Error: cannot open file" << endl;
  exit(1);
}
list<string> lines;
string line;
while (getline(infile, line)) {
  lines.push_back(line);
}

How it works:

  • The getline function will read an entire line from a stream into a string object
  • getline can be used as the test in a while loop; the loop will terminate as soon as getting a whole line from the stream fails