a ifstream variable cannot open the same file twice?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Xiaozhou.Yin@gmail.com

    a ifstream variable cannot open the same file twice?

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

  • Victor Bazarov

    #2
    Re: a ifstream variable cannot open the same file twice?

    Xiaozhou.Yin@gm ail.com wrote:
    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
    --
    Please remove capital 'A's when replying by e-mail
    I do not respond to top-posted replies, please don't ask


    Comment

    Working...