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.clear
– then 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
- clear
- seek
otherwise the next getline operation failed (MSVC v120)