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

merging two files into one in c++ and display it contents

本文关键字:文件 一个 显示 C++ 两个 合并      更新时间:2023-10-16

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

#include<iostream>
#include<conio.h>
#include<fstream>
using namespace std;
class emp
{
      int num,age;
      char name[20],dep[5];
      public:
          void getdata()
          {
             cout<<"nn  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<<"tt"<<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<<"nn 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<<"nntt Merged file contents nntt";
    display();
    getch();
    return 0;
} 

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

不要使用这样的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();
  }