James MV
James MV

Reputation: 8717

Rewind ifSteam in C++

I'm aware this has been asked a few time before and I read the threads related to it but the solutions there didn't work for me.

ifstream myFile;

myFile.open("largefile.txt");

    if (myFile.is_open())
        {
            while (!myFile.eof( ))  //step through each line until end of file
            {
                myFile>> str;
                if(str.size() < 5){
                    amount++;
                }
            }
        }

    myFile.seekg(0, ios::beg);

if (myFile.is_open())
        {
            for(int i=0; i != random_integer; i++)  //step through each line until random line reached
            {
                myFile>> str;
                if(i == random_integer-1){
                cout << "\n";
                cout << str;
                cout << "\n";
                cout << str.size();
                }
            }
        }
        myFile.close();

I read that using EOF in the while statement was a bad idea, whats the alternative? And how can I rewind for the second loop as seekg isn't working out, I don't want to have to close the file and open again, and the file is to large to read into an array really?

TIA, I'm sure this is an easy fix I'm just very new to C++.

Upvotes: 0

Views: 934

Answers (2)

CashCow
CashCow

Reputation: 31445

myFile >> str is not guaranteed to work just because you checked for end of file, because that is a flag only set when EOF has been read, not when it is about to be read.

Instead you should do:

while( myFile >> str )

You also need to clear your stream before you use it again (with seekg). One of the unfortunate things about streams is that they hold state as flags and they can trip you up if you are not careful.

myFile.clear();

then continue.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153919

Instead of testing eof() (which doesn't work correctly), you should just verify that each input has worked, by using the stream in a boolean context:

while ( myFile >> str ) {
    //  ...
}

Once it has failed, of course, the stream is in a failed state, which must be reset before any further operations are allowed:

myFile.clear();
myFile.seekg( 0, std::ios_base::beg );

Upvotes: 5

Related Questions