关于文件存储的代码,运行是出现乱码,求教!
程序代码:
/* 编程实现以下功能: (1) 按职工号由小到大的顺序将5个员工的数据(包括号码,姓名年龄,工资)输出到磁盘文件中保存. (2)从键盘输入两个员工(职工号大于已有的职工号),增加到文件的末尾。 (3)将磁盘文件中的数据全部读入程序然后在显示器显示. (4)从键盘输入一个号码,从文件中查找有无此职工号,如有则显示此职工是第几职工,以及此职工的全部数据, 如果没有就输出"无此人".可以反复多次查询,如果输入查找的职工号为0,就结束查询. 要求:用类和对象数组实现. */ //问题:输出第一个员工数据时正常,但从第二个数据开始都是乱码 #include<iostream> #include<fstream> #include<stdio.h> #define LEN sizeof(struct Worker) using namespace std; struct Worker { int number; char name[100]; int age; int wage; friend ostream & operator<<(ostream &output,Worker &w); }; struct Worker w[5]={{10101,"Li Lin",39,8000},{10102,"Zhang Fun",40,10000},{10104,"Zhang Min",34,7000}, {10103,"Wang Min",34,7000},{10105,"Wang Lin",34,8000}}; ostream & operator<<(ostream &output,Worker &w) { output<<"工号"<<w.number<<endl; output<<"姓名"<<w.name<<endl; output<<"年龄"<<w.age<<endl; output<<"工资"<<w.wage<<endl; return output; } void build_data(struct Worker w)//新建结构体数据 { cout<<"请输入职工数据:"<<endl; cout<<"工号:"; cin>>w.number; cout<<"姓名(请勿用空格简短):"; cin>>w.name; cout<<"年龄:"; cin>>w.age; cout<<"工资:"; cin>>w.wage; } void save_to_file(struct Worker w)//向磁盘文件添加数据的函数 { ofstream outfile("work.dat",ios::out|ios::binary); if(!outfile) { cerr<<"新数据储存失败!"<<endl; abort(); } outfile.seekp(0,ios::end); outfile.write((char *)&w,sizeof(w)); outfile.close(); cout<<"新数据储存完毕。"<<endl; } Worker seek(int n) { struct Worker w; ifstream infile("work.dat"); infile.seekg(n*LEN); infile.read((char *)&w,LEN); infile.close(); return w; } void research(int num,int n) { struct Worker w; int i; for(i=0;i<n+5;i++) { w=seek(i); if(w.number==num) { cout<<"该员工是第"<<i+1<<"个员工"<<endl; cout<<w<<endl; break; } } if(i==n+5) cout<<"无此人。"<<endl; } int main() { int i; for(int j=0;j<4;j++)//冒泡法将已有的5个员工的数据按工号由小到大进行排序 { for(i=0;i<4-j;i++) { if(w[i].number>w[i+1].number) { struct Worker temp; temp=w[i]; w[i]=w[i+1]; w[i+1]=temp; } } } ofstream outfile("work.dat",ios::out|ios::binary);//用fstream类定义输入输出二进制文件流对象iofile if(!outfile) { cerr<<"打开文件错误!"<<endl; abort(); } for(i=0;i<5;i++)//向磁盘文件输出5个职工的数据 outfile.write((char *)&w[i],sizeof(w[i])); outfile.close(); cout<<"请输入要添加的职工数据数量:"; int n; cin>>n; for(i=0;i<n;i++)//向磁盘文件添加新的职工数据 { build_data(w[0]); save_to_file(w[0]); } cout<<"\n全部员工数据:\n"; for(i=0;i<n+5;i++)//循环输出员工数据 { cout<<seek(i)<<endl; } int num=1; while(num) { cout<<"请输入要检索的工号:"; cin>>num; research(num,n); } return 0; }