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