Returning to beginning of file after getline

前端 未结 3 522
你的背包
你的背包 2020-12-02 17:14

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

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

Where ifile is an ifstream and line

相关标签:
3条回答
  • 2020-12-02 17:28

    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);
    
    0 讨论(0)
  • 2020-12-02 17:38

    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);
    
    0 讨论(0)
  • 2020-12-02 17:45

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

    1. clear
    2. seek

    otherwise the next getline operation failed (MSVC v120)

    0 讨论(0)
提交回复
热议问题