图书管理程序

题目

设计一个管理图书目的简单程序,提供的基本功能包括:可连续将新书存入文件“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);
            }
        }
    }
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值