c++不知道怎么删除txt文件里的指定内容C/C++ code#include iostream#include string#include fstream
c++不知道怎么删除txt文件里的指定内容
- C/C++ code
#include <iostream>#include <string>#include <fstream>#include <sstream>#include <vector>using namespace std;class Goods{ public: Goods(int Index, string Name, double Price, int Account); Goods(); ~Goods(); int GetIndex (void) const; //获取商品编号 string GetName (void) const; //获取商品名称 double GetPrice (void) const; //获取商品价格 int GetAccount (void) const; //获取商品数量 bool SetIndex (int Index) ; //判断商品编号 bool SetName (string Name); //判断商品名称 double SetPrice (double Price); //设置商品数量 int SetAccount (int Account) ; //设置商品价格 private: int G_Index; //商品编号 string G_Name; //商品名称 double G_Price; //商品价格 int G_Account; //商品数量 };Goods::Goods(int Index, string Name, double Price, int Account) //构造函数 { G_Index = Index; G_Name = Name; G_Price = Price; G_Account = Account;}Goods::Goods() //默认构造函数 {}Goods::~Goods() {}int Goods::GetIndex(void) const{ return G_Index;}string Goods::GetName(void) const{ return G_Name;}double Goods::GetPrice(void) const{ return G_Price;}int Goods::GetAccount(void) const{ return G_Account;}bool Goods::SetIndex(int index){ if( G_Index == index) return false; else return true;}bool Goods::SetName(string name){ if( G_Name == name) return false; else return true;}double Goods::SetPrice(double Price){ G_Price = Price;}int Goods::SetAccount(int Account){ G_Account = Account;}class GoodsManage //商品管理 { public: vector<Goods> good; //从网上下的代码,它可以将一个字符串(按照特定字符)分割成几个子串。 //例如,设要分割的字符串为"11,22,33",分割符为",",则分割后的结果 //为3个子串,分别是"11","22"和"33"。 void split( string src, string token, vector<string>& vect) //分割的字符串, 分割符, 分割后的结果存储在vect里 { int nend=0; int nbegin=0; while(nend != -1) { nend = src.find_first_of(token, nbegin); if(nend == -1) vect.push_back(src.substr(nbegin, src.length()-nbegin)); else vect.push_back(src.substr(nbegin, nend-nbegin)); nbegin = nend + 1; } } void MInit() //管理初始化 { ifstream file("goods.txt"); //如果指定的文件存在,则取出存储在文件里的vector对象,用它的值更新 AccountManage里的vector对象 //否则,不更新 AccountManage里的vector对象 if(file) { string str; //读一行数据 //循环的从文件中读数据,一次读一行数据 while(getline(file, str,'\n')) { //将读出的一行数据,转换为相应的Account对象 //将字符串分割 vector<string> vect; split(str,",",vect); int index; stringstream s; s<<vect.at(0); s>>index; string name = vect.at(1); double price; stringstream ss; ss<<vect.at(2); ss>>price; int account; stringstream sss; sss<<vect.at(3); sss>>account; //创建帐户 Goods CGoods(index, name, price, account); good.push_back(CGoods); } file.close(); } } void GDelIndex() //按商品编号删除 { int index;di: cout<<"请输入你要查询的商品编号"<<endl; cin>>index; int size = good.size(); for(int i=0; i<size; i++) { Goods CGoods = good.at(i); if(!CGoods.SetIndex(index)) { break; } else { cout<<"你要删除商品编号不存在,请重新输入!"<<endl<<endl; goto di; } } void GDelName() //按商品名称删除 { } void GDelAll()//删除所有商品 { }};
[解决办法]
所谓修改删除文件a某位置的内容,其实是读打开文件a,再将‘a中修改删除位置之前的内容+修改删除的内容+a中修改删除位置之后的内容’保存到文件b,关闭文件a,删除文件a,将文件b改名为与之前文件a相同的名字,仅此而已。
