C++图书管理案例

Book类存储一本图书信息。

class Book {
public:
    string bookId;
    string title;
    float price;
    //构造函数
    Book(string myBookId,string myTitle,float myPrice) {
        bookId = myBookId;
        title = myTitle;
        price = myPrice;
    }
    void printBook() {
        cout << bookId << "\t" << title << "\t" << price << endl;
    }
};

BookLibrary类代表图书馆,起管理图书的作用。

class BookLibrary {
public:
    vector<Book> books;
    //查找图书
    int findIndex(string myId) {
        for (int i = 0; i < books.size(); i++)
        {
            if (books[i].bookId == myId) {
                return i;
            }
        }
        return -1;
    }
    //删除图书
    void deleteBook(string myId) {
        for (int i = 0; i < books.size(); i++)
        {
            if (books[i].bookId == myId) {
                books.erase(books.begin() + i);
            }
        }
    }
    //插入图书
    void pushBook(Book myBook) {
        books.push_back(myBook);
    }
    //图书列表
    void listBook() {
        cout << "编号" << "\t" << "标题" << "\t" << "价格" << endl;
        for (int i = 0; i < books.size(); i++)
        {
            books[i].printBook();
        }
    }
};

主函数包含一个功能选择的界面,有3个功能:插入图书、删除图书、图书列表。
插入图书:用户输入编号、标题、价格,将此书存入图书馆。
删除图书:用户输入要删除图书的编号,从图书馆删除此书。
图书列表:打印图书馆所有图书。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    BookLibrary library = BookLibrary();
    while (true)
    {
        cout << "1.插入图书" << endl;
        cout << "2.删除图书" << endl;
        cout << "3.图书列表" << endl;
        cout << "请输入1或2或3:" << endl;
        int select;
        cin >> select;
        if (select == 1) {
            cout << "请输入编号:" << endl;
            string bookId;
            cin >> bookId;
            //cout << bookId << endl;
            cout << "请输入标题:" << endl;
            string title;
            cin >> title;
            cout << "请输入价格:" << endl;
            float price;
            cin >> price;
            Book newBook = Book(bookId, title, price);
            library.pushBook(newBook);
            //library.books[0].printBook();
            cout << "插入成功" << endl;
        }
        else if(select == 2){
            cout << "请输入编号:" << endl;
            string deleteId;
            cin >> deleteId;
            library.deleteBook(deleteId);
            cout << "删除成功" << endl;
        }
        else {
            library.listBook();
        }
    }
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值