Search code examples
c++vectorstlifstream

reading from ifstream file gives wrong size


I have a .txt file containing 6291456 numbers and nothing else. After reading all out and push_back into a vector, the vector.size() function returns 6291457. Where does this additional element come from?

    int disparity;
    ifstream disparity_txt;
    disparity_txt.open(path);
    while(!disparity_txt.eof())
    {
        disparity_txt >> disparity;
        vec_disparities.push_back(disparity);
    }
    cout << vec_disparities.size() << endl;
    disparity_txt.close();

Solution

  • Don't use while(!disparity_txt.eof()) it does not do what you think (eof will only be set after the end of the stream is read, so typically the last iteration is wrong) :

    Do :

    while(disparity_txt >> disparity)
    {
        vec_disparities.push_back(disparity);
    }