在c ++中将两个文件合并为一个并显示其内容

时间:2013-09-24 08:28:27

标签: c++ file eof

程序创建两个文件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;
} 

2 个答案:

答案 0 :(得分:0)

当您阅读 BEYOND 最后一个字符时,会设置EOF状态。 所以你应该在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();
  }   

答案 1 :(得分:0)

不要那样使用file1.eof

请在其他帖子中找到数百个答案。

示例:this

修复如下:

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