0

程序创建了两个文件emp.txt和sal.txt。这两个文件的内容最终都放在了empdetails.txt中。一切正常,但是显示函数:-void display()正在显示最后一条记录TWICE。为什么最后一条记录显示两次???

#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;

class emp
{
      int num,age;
      char name[20],dep[5];

      public:
          void getdata()
          {
             cout<<"\n\n  Name   = ";
             cin>>name;
             cout<<"\n Emp Num   = ";
             cin>>num;
             cout<<"\n Department= ";
             cin>>dep;
             cout<<"\n Age       = ";
             cin>>age;
          }
          void display1()
          {  
            cout<<"\n"<<name<<"\t"<<num<<"\t"<<dep<<"\t\t"<<age;
          }  

};

class sal
{
      float gs,ns;
       public:
           void getsal()
           {
             cout<<"\n Gross sal = ";
             cin>>gs;
             cout<<"\n Net sal   = ";
             cin>>ns;
           }
           void display2()
           {
             cout<<"\t"<<gs<<"\t"<<ns;
           }          
};

void display()
{
   emp e;sal s;
   ifstream fil1;

   fil1.open("empdetails.txt",ios::in);

   cout<<"\n\n Name \t Emp Num \t Dep \t Age \t Gross Sal \t Net Sal \n";  

  while(!fil1.eof())
  {
    fil1.read((char*)&e,sizeof(e));
    e.display1();

    fil1.read((char*)&s,sizeof(s));
    s.display2();
  }   
}

int main()
{
    int n;
    emp e1;sal s1;
    ofstream fil1,fil2,fil3;

    fil1.open("emp.txt",ios::out);
    fil2.open("sal.txt",ios::out);
    fil3.open("empdetails.txt",ios::out);

    cout<<"\n How many employee details do you want to enter = ";
    cin>>n;

    cout<<"\n Enter the deatils one by one \n";
    for(int i=0;i<n;i++)
    {
        e1.getdata();
        fil1.write((char*)&e1,sizeof(e1));

        s1.getsal();
        fil2.write((char*)&s1,sizeof(s1));

        fil3.write((char*)&e1,sizeof(e1));
        fil3.write((char*)&s1,sizeof(s1));
    }
    fil1.close();
    fil2.close();
    fil3.close();

    cout<<"\n\n\t\t Merged file contents \n\n\t\t";
    display();
    getch();
    return 0;
} 
4

2 回答 2

0

EOF 状态在您读取BEYOND最后一个字符时设置。所以你应该在read().

  while(true)
  {
    fil1.read((char*)&e,sizeof(e));
    // do the checking right after a read()
    if (fil1.eof())
      break;
    e.display1();

    fil1.read((char*)&s,sizeof(s));
    s.display2();
  }   
于 2013-09-24T08:40:22.627 回答
0

不要那样file1.eof使用

请参阅其他帖子已有数百个答案。

示例:这个

修复如下:

  while(fil1.read((char*)&e,sizeof(e)))
  {
    //fil1.read((char*)&e,sizeof(e));
    e.display1();

    fil1.read((char*)&s,sizeof(s));
    s.display2();
  } 

或者

如果您仍想使用eof:-

while(true)
  {
    fil1.read((char*)&e,sizeof(e));
    if (fil1.eof()) //Check here after reading 
      break;
    e.display1();

    fil1.read((char*)&s,sizeof(s));
    s.display2();
  }
于 2013-09-24T08:40:41.483 回答