0

Both of the while loops work individually. However, the second while loop in my code won't work when the while loop above it is present. I need both while loops to work together.

#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(){
    string line, line1, line2;
    int count = 0;
    int track = 0;
    int stop;
    ifstream file ("ai.txt");
    while (getline(file, line2)){
        count++;
    }
    file.seekg (0L, ios :: beg);
    stop = count - 10;
    while (getline(file, line)){
        track++;
        if (track >= stop){
            for (int num = 1; num <=10; num++){
                getline(file,line1);
                cout << line1 << endl;   
            }
        }
    }

}

The code should output the last ten lines of any text file.

1 Answer 1

2

So you consumed all the lines from a file stream.

Then you seeked the stream back to the beginning of the file.

And you started consuming lines again.

What you didn't do is clear the "end of file" flag from the stream that was set when it reached the end the first time. With that flag still in place, the stream's useless.

Add file.clear() before file.seekg(...).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.