Reusing an ifstream variable doesn't work

To get some practice with fstreams I adapted Maggi Maggi's code from this thread (http://www.cplusplus.com/forum/general/59984/) to read the testdata input files.

The article "Input/Output with files" says:

myfile.close();

Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.


I tried reusing the ifstream variable infile in the code below to open a second text file but the data I get is incorrect and is possibly garbage. For instance I get 899 and 131 instead of 2 and 5706.

Using a new ifstream variable for opening the second text file gets the correct data.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <fstream>

using namespace std;
int main()
{
    int n, pof=0, pos=0, f, s, l=0, w ;
    int i = 0;
    ifstream infile("F:\\Basic-2-testdata\\2.in");
    if(infile.is_open())
    {
        infile >> n;
        while (infile.good())
        {
            infile>>f>>s;
            pof += f;
            pos += s;
            //cout<<"Round"<<++i<<" "<<pof<<" "<<pos<<" Lead "<<pof-pos<<endl; 
            if (abs(pof-pos)>abs(l)){l = pof-pos;}       
        }
        infile.close();                            // close infile here
        if (l>0) {w=1;} else {w=2;}
        cout<<"Winner is player"<<w<<" with greatest lead of "<<abs(l)<< endl;
        infile.open("F:\\Basic-2-testdata\\2.out");  // try to reuse infile here
        if (infile.is_open())
        {
            infile>>f>>s;
            cout<<"Test out data: Winner is player"<<f<<" Lead "<<s<<endl;
            infile.close();
        }
        else
        {
            cout << "unable to open outfile"<< endl;
        }
    }
    else
    {
        cout << "unable to open infile" << endl;
    }
    system("pause");
    return 0;
}
Last edited on
You might need to call infile.clear(); after infile.close(); to clear any error flags.
That fixed it. Thanks.
Topic archived. No new replies allowed.