Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning to beginning of file after getline

Tags:

c++

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?

like image 938
bq54 Avatar asked Mar 17 '11 17:03

bq54


People also ask

How do I go back to the beginning of a file in C++?

The rewind() function in C++ sets the file position indicator to the beginning of the given file stream.

Does Getline go to the next line?

So getline never reads a second line because getline is never called a second time - the code gets stuck in the infinite loop before that can happen.

How do I count the number of lines in a file C++?

How To Count Lines In A File In C++? To count the lines in a file in c++, we will open the file in the read mode only as there are no output operations needed. Once the file is open we will read the file line by line using the getline() function and count the number of lines.


1 Answers

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); 
like image 199
Konrad Rudolph Avatar answered Sep 16 '22 13:09

Konrad Rudolph