Returning to beginning of file after getline

C++

C++ Problem Overview


So i've read all the lines from a file thusly

while (getline(ifile,line))
    {
        // logic
    }

Where ifile is an ifstream and line is a string

My problem is I now want to use getline over again, and seem to be unable to return to the beginning of the file, as running

cout << getline(ifile,line);

Will return 0

I've attempted to use:

ifile.seekg (0, ios::beg);

To no avail, it seems to have no effect. How do I go back to the start of the file?

C++ Solutions


Solution 1 - C++

Since you have reached (and attempted to read past) the end of the file, the eof and fail flags will be set. You need to clear them using ifile.clearthen try seeking:

ifile.clear();
ifile.seekg(0);

Solution 2 - C++

This is because the eof flag has been set on the stream - due to you reaching the end of the file. so you have to clear this as an additional step.

Eg

ifile.clear();
ifile.seekg (0, ios::beg);

Solution 3 - C++

FYI: In my case, the order DID matter, thus

  1. clear
  2. seek

otherwise the next getline operation failed (MSVC v120)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbq54View Question on Stackoverflow
Solution 1 - C++Konrad RudolphView Answer on Stackoverflow
Solution 2 - C++Angus ComberView Answer on Stackoverflow
Solution 3 - C++iko79View Answer on Stackoverflow