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<fstrea m>
#include<iostre am>
using namespace std;
int count(ifstream& fin);
void find_median(ifs tream& 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(ifs tream& 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<<end l;
}
else
{
m=n/2;
for(i=1;i<=m;++ i)
fin>>next;
median=next;
fin>>next;
median=(next+me dian)/2;
cout<<"\nThe median is:"<<median<<e ndl;
}
return;
}
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<fstrea m>
#include<iostre am>
using namespace std;
int count(ifstream& fin);
void find_median(ifs tream& 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(ifs tream& 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<<end l;
}
else
{
m=n/2;
for(i=1;i<=m;++ i)
fin>>next;
median=next;
fin>>next;
median=(next+me dian)/2;
cout<<"\nThe median is:"<<median<<e ndl;
}
return;
}
Comment