c++ifstreameofseekg

Reading from a particular fill till the last line in C++


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();
}

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.