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();
}
}
}
标签:cout,bookId,C++,案例,Book,books,图书,string
From: https://blog.csdn.net/zhourongxiang1/article/details/136676764