Question

I have a text file with many lines. I want to store each line in a vector of strings. I want to read from the file until the last line is reached. I used the EOF function but it seems to store blank lines after the last line also. Here's a snippet of my code. text_list is a vector in which all the lines of the file are stored.

void TextBuddy::storeDataFromFileInVector(string filename){
ifstream infile;
int numbers;
string textMessage;
infile.open(filename);

while (!infile.eof()){
    getline(infile, textMessage);
    text_list.push_back(textMessage);
}
infile.close();
}
Was it helpful?

Solution

eof() does not look into the future. So, when you are right before EOF, you will read it also into your vector and probably corrupt it.

A better way to read all lines into a vector is:

string line;
while(getline(inFile, line)
    text_list.push_back(line);

Your loop will break once you've read an EOF or when any other error has occured.

Another method is using iterators and the algorithm library:

copy(istream_iterator<string>(inFile), istream_iterator<string>(),
     back_inserter(text_list));

It's up to you which one you prefer.

OTHER TIPS

Blank lines, plural? You should check if it reached EOF before pushing to the list.

infile.open( filename );

getline( infile, textMessage );
while( !infile.eof() )
{
    text_list.push_back( textMessage );
    getline( infile, textMessage );
}

edit: KasF's answer is better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top