//Book.h
#pragma once
#include <string>
using namespace std;
class Book
{
private:
string number;
string name;
string author;
string press;
string price;
public:
Book();
~Book();
static void addbook();
static void subbook();
static void modbook();
};
//Book.cpp
#include "Book.h"
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
Book::Book()
{
ofstream ofile;
ofile.open("book.txt");
ofile << '\n';
ofile.close();
}
Book::~Book()
{
}
void Book::addbook()
{
fstream ofile;
ofile.open("book.txt",ios::app|ios::ate|ios::out);
cout << "请分别输入书的编号、书名、作者、出版社、单价:";
string number, name, author, press;
string price;
cin >> number >> name >> author >> press >> price;
ofile<< number << ',' << name << ',' << author << ',' << press << ',' << price <<'|';
cout << "添加成功!" << endl;
ofile.close();
}
void Book::subbook()
{
fstream file;
file.open("book.txt",ios::in);
string tmp , tmp1;
file >> tmp;
cout << tmp;
//file.close();
cout << "请输入待删除图书的书名或编号:";
cin >> tmp1;
int qian, hou, zhong;
zhong = tmp.find(tmp1);
qian = tmp.rfind('|', zhong);
hou = tmp.find('|', zhong);
tmp=tmp.erase(qian + 1, hou);
file.close();
ofstream ofile;
cout << tmp;
ofile.open("book.txt", fstream::trunc);
file << tmp;
cout << "删除成功!" << '\n'; //为什么无法替换file里的内容呢?
}
void Book::modbook()
{
fstream file;
file.open("book.txt", fstream::in);
string tmp, tmp1;
file >> tmp;
cout << "请输入待修改图书的书名或编号:";
cin >> tmp1;
int qian, hou, zhong;
zhong = tmp.find(tmp1);
qian = tmp.rfind('|', zhong);
hou = tmp.find('|', zhong);
string number, name, author, press;
string price;
cout << "请重新输入该图书的信息(按照编号、书名、作者、出版社的顺序):";
cin >> number >> name >> author >> press >> price;
string strtmp = '|' + number + ',' + name + ',' + author + ',' + press + ',' + price + '|';
tmp.replace(qian, hou-1, strtmp);
file.open("book.txt", fstream::out | fstream::trunc);
file << tmp;
cout << "修改成功!" << '\n';
file.close();
}
//源.cpp
#include <iostream>
#include <string>
#include <fstream>
#include <iomanip>
#include "Book.h"
using namespace std;
int main()
{
Book::addbook();
Book::addbook();
Book::subbook();
Book::modbook();
system("pause");
return 0;
}
额,这是所有代码,没有写在同一个cpp里······ |