So I'm using the >> operator to read objects from a file one by one. I am simultaneously counting the objects and need to read them again one by one to print from a certain point.

inFile.clear();
inFile.seekg( 0, ios::beg);

Doesn't seem to work for me, and I assume it is because I am using inFile >> variable instead of the get function. What would be the proper way of seeking back to the start of a file if you use the >> function so I can read input from the same file twice without closing it and reopening it.

If you're going back and forth like that a lot you might be better of loading the file into some sort of structure, an array or maybe a list. This allows back and forth access much more easily.

The extraction operator (>>) should have nothing to do with your error because seekg(0, ios::beg) is modifying the internal stream pointer.

For example, the code:

#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    ifstream f ("example.txt");
    int x, y;

    for (int i=0; i<3; i++) {
        f >> x >> y;
        cout << x << " " << y << endl;
        f.seekg(0, ios::beg);
    };

    f.close();

    return 0;
}

where "example.txt" is:

1 2 9
3 4 10
5 6 11
7 8 12

with or without the third column, returns

1 2
1 2
1 2

Could you provide more details about your code?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.