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

user1334858 picture user1334858 · Oct 1, 2013 · Viewed 26k times · Source

I am trying to use std::getline() in my project to read in a text file into an array of strings.

Here is my code:

ifstream ifs ( path );
string * in_file;
int count = 0;
while ( !ifs.eof() )
{
    ++count;
    if ( count == 1 )
    {
        in_file = new string[1];
    }
    else
    {
            // Dynamically allocate another space in the stack
    string *old_in_file = in_file;
    in_file = new string[count];
            // Copy over values
    for ( int i = 0 ; i < ( count - 1 ) ; i++ )
    {
        in_file[i] = old_in_file[i];
    }
    delete[] old_in_file;
    }
            // After doing some debugging I know this is the problem what am I 
            // doing wrong with it?
    getline(ifs,in_file[count - 1]);
}

So after doing some decoding I know that the getline() is not placing any value in the array of strings. It seems to place a null string in the array.

The goal is to read in a text file like:

Hello
Bye
See you later

The array will be filled like:

in_file [0] = Hello
in_file [1] = Bye
in_file [2] = See you later

Answer

P0W picture P0W · Oct 1, 2013

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];