We're a community of 1076K IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,075,983 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

taking input from file more than once

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.

3
Contributors
2
Replies
2 Hours
Discussion Span
4 Months Ago
Last Updated
3
Views
Dewey1040
Junior Poster
140 posts since Dec 2008
Reputation Points: 17
Solved Threads: 3
Skill Endorsements: 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.

tinstaafl
Nearly a Posting Virtuoso
1,324 posts since Jun 2010
Reputation Points: 355
Solved Threads: 228
Skill Endorsements: 14

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?

CGSMCMLXXV
Junior Poster in Training
54 posts since Jan 2013
Reputation Points: 5
Solved Threads: 7
Skill Endorsements: 0

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
 
© 2013 DaniWeb® LLC
Page rendered in 0.0578 seconds using 2.7MB