在 C++ 中将两个文件合并为一个文件并显示其内容
merging two files into one in c++ and display it contents
程序创建两个文件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();
}
相关文章:
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 挂起和取消挂起一个文件DLL
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- C++试图读取一个文件并输出到另一个文本文件
- 如何从另一个文件继承私有成员变量和公共函数
- 在 Windows 上,是否可以让 dll 在不使用 PATH 环境变量的情况下在另一个文件夹中查找依赖项?
- 如何打开并写入一个名称取自C++中字符串的文件
- 构建一个由C和C++文件组成的库
- c++多进程编写一个唯一的文件
- 如何使用CLion在Mac上创建一个新的.txt文件
- 如何将class.cpp和class.hpp编译为一个.o文件
- 写入文件会产生一个空文件或根本没有文件
- 如何将不同的可执行文件合并到一个窗口框架中进行编码?像浏览器一样
- 生成一个生成文件,该生成文件使用Automake在一个步骤中编译和链接所有源文件
- 为什么我的 heap.h 文件给我一个LNK2001错误?
- Pantheios 不使用 MFC 应用程序写入一个文件(一个 exe + 两个 DLL)
- 在C++中一次读取一个文件一个int
- 输入/输出文件(一个字母的大写)
- 如何使用两个预编译的头文件.一个用于托管代码,另一个用于非托管代码.xxx.PCH不是一个有效的预编译头文件