Ben
Ben

Reputation: 1349

Reading a text file from the first line multiple times (C++)

I'm using "getline" to read some lines in a text file. It works as it should, but I'm calling the method multiple times.

while(getline(file, line))
{
    //Do something
}

//More code in between

while(getline(file, line))
{
    //Do something else
}

The problem is that when I call "getline" the second time it starts reading from where it previously finished (e.g. If the first while loop ends at the second line then the next loop starts at the third line). How can I ensure that my program reads the file from the first line every time?

Upvotes: 2

Views: 6790

Answers (2)

Xarylem
Xarylem

Reputation: 398

If you need that same first line multiple times I think you should reconsider your strategy.

  1. Just read the line once.
  2. Save it in a variable (or just keep it in the variable "line" you already have).
  3. Close the file.

You would avoid a lot of not necessary I/O operations...

Nonetheless as other people suggested if by any reason you want to procede with this approach you need to insert:

myinputstream.clear();             //clear the buffer
myinputstream.seekg(0, ios::beg);  //reset the reading position to beginning

between each attempt to read the same file. And do not forget to close it eventually.

myinputstream.close();

Upvotes: 6

XWiśniowiecki
XWiśniowiecki

Reputation: 1843

There's a seekg() function that should help http://www.cplusplus.com/reference/istream/istream/seekg/

 iostream::seekg (0, iostream::beg);

will move you at the beggining of the stream

Upvotes: 3

Related Questions