怎样删除文件中的某个数据和更新某个数据
#include<iostream>#include<fstream>
#include<string>
using namespace std;
class Staff
{
protected:
int num,age;
string name;
public:
void fp()
{
ofstream ap;
ap.open("staff.txt");
if(!ap)
{
cout<<"打开失败";
exit(1);
}
ap.close();
}
void input()
{
ofstream ap("staff.txt");
cout<<"输入名字"<<endl;
cin>>name;
cout<<"编号"<<endl;
cin>>num;
cout<<"年龄"<<endl;
cin>>age;
ap<<"名字"<<name<<" "<<"编号"<<num<<" "<<"年龄"<<age;
}
void show()
{
string s;
ifstream fp;
fp.open("staff.txt");
while(getline(fp,s))
cout<<s<<endl;
fp.close();
}
};
class engieer:public Staff
{
public:
string major;
string workname;
void input1()
{
ofstream ap("staff.txt",ios::out|ios::app);
cout<<"请输入数据"<<endl;
cout<<"编号"<<endl;cin>>num;
cout<<"年龄"<<endl;cin>>age;
cout<<"名字"<<endl;cin>>name;
cout<<"专业"<<endl;cin>>major;
cout<<"职称"<<endl;cin>>workname;
ap<<"编号:"<<num<<" "
<<"年龄"<<age<<" "
<<"名字"<<name<<" "
<<"专业"<<major<<" "
<<"职称"<<workname<<" "<<endl;
ap.close();
}
};
class leader:public Staff
{
public:
string bm;//部门
string zc;//职称
void input2()
{
ofstream ap("staff.txt",ios::out|ios::app);
cout<<"请输入数据"<<endl;
cout<<"编号"<<endl;cin>>num;
cout<<"年龄"<<endl;cin>>age;
cout<<"名字"<<endl;cin>>name;
cout<<"部门"<<endl;cin>>bm;
cout<<"职称"<<endl;cin>>zc;
ap<<"编号:"<<num<<" "
<<"年龄"<<age<<" "
<<"名字"<<name<<" "
<<"部门"<<bm<<" "
<<"职称"<<zc<<" "<<endl;
ap.close();
}
};
class company:public Staff
{
public:
int g;
Staff w;
static int j;
static int k;
engieer a[1000];
leader b[100];
void add();//增加
void new1();//更新
void look();//查询
void del();//删除
void cz();
};
int company::j=0; int company::k=0;
void company::add()
{
int i;
cout<<"请选择增加项目1.工程师2.主任:"<<endl;
cin>>i;
if(i==1)
{
a[j].input1();
j++;
}
else if(i==2)
{
b[k].input2();
k++;
}
else cout<<"输入错误....."<<endl;
}
void company::look()
{
w.show();
}
void company::new1()
{
}
void company::del()
{
}
void company::cz() //重组文件
{
cout<<"重组数据就是删除原文件全部内容,并且重新写入数据,请谨慎!"<<endl;
int i;
cout<<"输入0退出,输入1继续"<<endl;
cin>>i;
cout<<" "<<endl;
if(i==0) return;
ofstream fp;
fp.open("staff.dat",ios::trunc);
if(!fp)
cout<<"文件写入错误!"<<endl;
cout<<"文件重组成功!"<<endl<<endl<<endl;
fp.close();
}
int main()
{
int w;
company c;
for(;;)
{
cout<<"请选择"<<endl;
cout<<"1.增加"<<endl;
cout<<"2.查询"<<endl;
cout<<"3.更新"<<endl;
cout<<"4.删除"<<endl;
cin>>w;
switch(w)
{
case 1:c.add();break;
case 2:c.look();break;
case 3:c.new1();break;
case 4:c.del();break;
default:cout<<"输入错误.......";break;
}
}
return 0;
}