a ifstream variable cannot open the same file twice?

X

Xiaozhou.Yin

Hi~
In the program,I first used the ifstream variable fin open the file
and,open it again after called the fin.close().But the fin is fieled
to open the file in the second time.The book I'm learning hadn't
picked out this.Is it a common problem?Or just occurs in Vc++6.0?
#include<fstream>
#include<iostream>
using namespace std;

int count(ifstream& fin);
void find_median(ifstream& fin,int n);
main()
{
char name[9];
int n;
ifstream fin;
cout<<"Please input the file name in five chars:";
cin>>name;
fin.open(name);
if(fin.fail())
{
cout<<"\nfailed in opening the file.\n";
exit(1);
}
n=count(fin);
fin.close();
fin.open(name);
if(fin.fail())
exit(1);
find_median(fin,n);
fin.close();
return 0;
}
int count(ifstream& fin)
{
int n;
double next;
n=0;
while(fin>>next)
n++;
return n;
}
void find_median(ifstream& fin,int n)
{
int m,i;
double next=0,median=0;
if((n%2)==1)
{
m=n/2+1;
for(i=1;i<=m;++i)
fin>>next;
cout<<"\nThe median is:"<<next<<endl;
}
else
{
m=n/2;
for(i=1;i<=m;++i)
fin>>next;
median=next;
fin>>next;
median=(next+median)/2;
cout<<"\nThe median is:"<<median<<endl;
}
return;
}
 
V

Victor Bazarov

Hi~
In the program,I first used the ifstream variable fin open the file
and,open it again after called the fin.close().But the fin is fieled
to open the file in the second time.The book I'm learning hadn't
picked out this.Is it a common problem?Or just occurs in Vc++6.0?

Don't forget to do

fin.clear();

to remove any error conditions that may have arisen with the other file.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top