1,105,229 Community Members

taking input from file more than once

Member Avatar
Dewey1040
Junior Poster
140 posts since Dec 2008
Reputation Points: 7 [?]
Q&As Helped to Solve: 3 [?]
Skill Endorsements: 0 [?]
 
0
 

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.

Member Avatar
tinstaafl
Postaholic
2,009 posts since Jun 2010
Reputation Points: 559 [?]
Q&As Helped to Solve: 400 [?]
Skill Endorsements: 35 [?]
 
0
 

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.

Member Avatar
CGSMCMLXXV
Junior Poster in Training
54 posts since Jan 2013
Reputation Points: 5 [?]
Q&As Helped to Solve: 7 [?]
Skill Endorsements: 0 [?]
 
0
 

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?

You
This article has been dead for over three months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article