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?
The rewind() function in C++ sets the file position indicator to the beginning of the given file stream.
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 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With