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;
}