How to use std::getline() to read a text file into an array of strings in C++? How to use std::getline() to read a text file into an array of strings in C++? arrays arrays

How to use std::getline() to read a text file into an array of strings in C++?


Never wrap reading from the stream with the following loop:

while ( !ifs.eof() )

At some websites, you will find an example telling you to do:

while ( ifs.good() )

which is a bit better than the first loop, yet still it is quite error prone and not advisable to do. Have a look at: Why is iostream::eof inside a loop condition considered wrong?

The most common ways of reading the files are either using std::getline when reading by lines:

std::string line;while ( std::getline(ifs, line) ) {    if (line.empty())                  // be careful: an empty line might be read        continue;                          ...}

or simply using >> operator when reading by words or extracting concrete types (e.g. numbers):

std::string word;while ( ifs >> word ) {                   ...}

And to your dynamically allocated C-style array of std::string objects: avoid dynamic allocation as much as possible. Believe me, you don't want to take care of memory management on your own. Prefer using objects with automatic storage duration. Take advantage of what the standard library provides.
As it was pointed out already: use STL containers such as std::vector instead of C-style arrays:

std::ifstream ifs(path);std::vector<std::string> lines;std::string line;while ( std::getline(ifs, line) ){    // skip empty lines:    if (line.empty())        continue;    lines.push_back(line);}


Why so trouble ?

Simply use std:vector of std::string

std::string str;std::vector <std::string> vec;while ( std::getline(ifs,str) ){  vec.push_back(str) ;}

If you really need an array of string

do :

string * in_file = new string[vec.size()];

And copy the elements from vec to in_file

for(size_t i=0;i<vec.size();i++) in_file[i] = vec[i];