题目
设计一个管理图书目的简单程序,提供的基本功能包括:可连续将新书存入文件“book.dat”中,新书信息加入到文件的尾部;也可以根据输入的书名进行查找;把文件“book.dat”中同书名的所有书显示出来。为简单起见,描述一本书的信息包括:书号,书名,出版社和作者。
相关阅读
完整代码
#include <bits/stdc++.h>
using namespace std;
class Book {
private:
string id;
string name;
string publisher;
string author;
public:
string getName() {
return this->name;
}
friend ifstream &operator>>(ifstream &in, Book &book);
friend istream &operator>>(istream &in, Book &book);
friend ofstream &operator<<(ofstream &out, Book book);
friend ostream &operator<<(ostream &out, Book book);
};
ifstream &operator>>(ifstream &in, Book &book) {
in >> book.id >> book.name >> book.publisher >> book.author;
}
istream &operator>>(istream &in, Book &book) {
in >> book.id >> book.name >> book.publisher >> book.author;
}
ofstream &operator<<(ofstream &out, Book book) {
out << book.id << " " << book.name << " " << book.publisher << " " << book.author;
}
ostream &operator<<(ostream &out, Book book) {
out << book.id << " " << book.name << " " << book.publisher << " " << book.author;
}
void Order(int &order) {
cout << "----------" << endl;
cout << "1.查找图书" << endl;
cout << "2.添加新书" << endl;
cout << "3.退出" << endl;
cout << "----------" << endl;
cout << "请选择命令:";
cin >> order;
}
int main() {
fstream file;
while (true) {
int order;
Order(order);
switch (order) {
case 1: {
int count = 0;
string name;
cout << "请输入要查找的书名:";
cin >> name;
file.open("book.dat");
while (!file.eof()) {
Book temp;
file >> temp;
if (temp.getName() == name) {
cout << temp << endl;
}
}
file.close();
cout << "查找完成,共找到 " << count << " 本图书!" << endl;
break;
}
case 2: {
Book newBook;
cout << "请输入要添加的图书信息:";
cin >> newBook;
file.open("book.dat", ios::app);
file << newBook;
file.close();
cout << "图书添加完毕!" << endl;
break;
}
case 3: {
exit(1);
}
}
}
}