Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

c++ - Returning to beginning of file after getline

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...