开发者

Returning to beginning of file after getline

开发者 https://www.devze.com 2023-02-18 00:10 出处:网络
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

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,开发者_如何学Cline);

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?


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


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


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

  1. clear
  2. seek

otherwise the next getline operation failed (MSVC v120)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号