编程序实现以下功能: (1) 按职工号由小到大的顺序将5个员工的数据(包括号码、姓名、年龄、工资)输出到磁盘文件中保存。 C++

2016-06-28 10:50:56  分类: c++程序设计第三版谭浩强课后答案  参与:

编程序实现以下功能: 
(1) 按职工号由小到大的顺序将5个员工的数据(包括号码、姓名、年龄、工资)输出到磁盘文件中保存。
(2) 从键盘输入两个员工的数据(职工号大于已有的职工号),增加到文件的末尾。
(3) 输出文件中全部职工的数据。
(4) 从键盘输入一个号码,从文件中查找有无此职工号,如有则显示此职工是第几个职工,以及此职工的全部数据。如没有,就输出“无此人”。可以反复多次查询,如果输入查找的职工号为0,就结束查询。

谭浩强c++程序设计第三版答案
以下是此题的【c源代码】
#include <iostream>
#include <fstream>
using namespace std;
struct staff
{int num;
 char name[20];
 int age;
 double  pay;
};
int main()
{staff staf[7]={2101,"Li",34,1203,2104,"Wang",23,674.5,2108,"Fun",54,778,
                  3006,"Xue",45,476.5,5101,"Ling",39,656.6},staf1;
 fstream iofile("staff.dat",ios::in|ios::out|ios::binary);
 if(!iofile)
  {cerr<<"open error!"<<endl;
   abort();
  }
 int i,m,num;
 cout<<"Five staff :"<<endl;
 for(i=0;i<5;i++)
   {cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
    iofile.write((char *)&staf[i],sizeof(staf[i]));}
 cout<<"please input data you want insert:"<<endl;
 for(i=0;i<2;i++)
   {cin>>staf1.num>>staf1.name>>staf1.age>>staf1.pay;
    iofile.seekp(0,ios::end);
    iofile.write((char *)&staf1,sizeof(staf1));}
  iofile.seekg(0,ios::beg);
  for(i=0;i<7;i++)
   {iofile.read((char *)&staf[i],sizeof(staf[i]));
    cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
   }
 bool find;
 cout<<"enter number you want search,enter 0 to stop.";
 cin>>num;
 while(num)
 {find=false;
  iofile.seekg(0,ios::beg);
  for(i=0;i<7;i++)
   {iofile.read((char *)&staf[i],sizeof(staf[i]));
    if(num==staf[i].num)
     {m=iofile.tellg();
      cout<<num<<" is No."<<m/sizeof(staf1)<<endl;
      cout<<staf[i].num<<" "<<staf[i].name<<" "<<staf[i].age<<" "<<staf[i].pay<<endl;
      find=true;
      break;
     }
   }
  if(!find)
    cout<<"can't find "<<num<<endl;
  cout<<"enter number you want search,enter 0 to stop.";
  cin>>num;
 }
  iofile.close();
  return 0;
}


来源:c++程序设计第三版谭浩强课后答案

本文链接:http://www.wb98.com/cjia/post/cjia_13.5.html


本站文章搜索:

<< 上一篇下一篇 >>

搜索

Tags列表

赞助商链接