如果雇员定义的是一个类(结构体改成类
怎么用文件呢
//1) 将五名员工的数据(包括员工编号、姓名、年龄和工资)按员工编号从小到大的顺序输出到磁盘文件中保存。
//(2) 从键盘输入一名员工的数据(员工编号大于现有员工编号),并将其添加到文件末尾。
//(3) 输出文件中所有员工的数据。
//(4) 从键盘输入一个数字,以确定文件中是否有此员工编号。如果是,将显示该员工的所有数据。如果没有,则输出“无人发现”。您可以重复查询。如果输入的员工编号为0,则查询将结束。
#include<bits/stdc++.h>
#include <fstream>
using namespace std;
struct staff{
int num;
char name[20];
int age;
double salary;
};
int main(){
staff staff_[7]={
2001,"Li",25,8500,
2002,"Wang",26,9000,
2003,"Zhang",27,9500,
2004,"Liu",28,9600,
2005,"Zheng",26,10000.1},staff_1;
fstream iofile("staff.dat",ios::in | ios::out|ios::binary); //以读写模式打开
if(!iofile){ //用is_open()判断是否打开
cerr<<"open error!"<<endl;
abort();
}
int num;
cout<<"Five staff:"<<endl;
for(int i=0;i<5;i++){
cout<<staff_[i].num<<" "<<staff_[i].name<<" "<<staff_[i].age<<" "<<staff_[i].salary<<endl;
iofile.write((char*)&staff_[i],sizeof(staff_[i]));//写入文件
}
cout<<"Please input the staff's information that you want to insert"<<endl;
cin>>staff_1.num>>staff_1.name>>staff_1.age>>staff_1.salary;
iofile.write((char*)&staff_1,sizeof(staff_1));
cout<<"All the staff"<<endl;
iofile.seekg(0,ios::beg);
int ntotal = 0;
while(!iofile.eof())
{ //这里用eof判断是否读取结束
iofile.read((char*)&staff_[ntotal],sizeof(staff_[ntotal]));
if(staff_[ntotal].num > 0 && staff_[ntotal].age>0 && staff_[ntotal].salary>0)
{
cout<<staff_[ntotal].num<<" "<<staff_[ntotal].name<<" "<<staff_[ntotal].age<<" "<<staff_[ntotal].salary<<endl;
ntotal++;
}
}
iofile.close();
cout<<"Please input the number that you want to search"<<endl;
cin>>num;
int flag=0;
while(flag ==0)
{
for(int i=0;i<ntotal;i++){
if(num==staff_[i].num){
cout<<num<<"is No."<<i+1<<endl;
cout<<staff_[i].num<<" "<<staff_[i].name<<" "<<staff_[i].age<<" "<<staff_[i].salary<<endl;
flag=1;
break;
}
}
if(flag==0){
cout<<"can't find!"<<endl;
cout<<"Please input again or enter 0 to stop!"<<endl;
cin>>num;
}
}
return 0;
}