书管理系统c++代码
cpp#include <iostream>
#include <vector>
#include <string>
using namespace std;
// 定义书籍结构体
struct Book {
string title;
string author;
int year;
};
// 定义书籍管理系统类
class BookManager {
private:
vector<Book> books;
public:
// 添加书籍
void addBook(const string& title, const string& author, int year) {
Book book = {title, author, year};
books.push_back(book);
}
// 删除书籍
void removeBook(const string& title) {
for (auto it = books.begin(); it != books.end(); ++it) {
if (it->title == title) {
books.erase(it);
cout << "书籍 \"" << title << "\" 已删除。" << endl;
return;
}
}
cout << "未找到书籍 \"" << title << "\"。" << endl;
}
// 查找书籍
void findBook(const string& title) {
for (const auto& book : books) {
if (book.title == title) {
cout << "书名: " << book.title << endl;
cout << "作者: " << book.author << endl;
cout << "出版年份: " << book.year << endl;
return;
}
}
cout << "未找到书籍 \"" << title << "\"。" << endl;
}
// 显示所有书籍
void displayAllBooks() {
if (books.empty()) {
cout << "没有书籍记录。" << endl;
return;
}
cout << "所有书籍信息:" << endl;
for (const auto& book : books) {
cout << "书名: " << book.title << endl;
cout << "作者: " << book.author << endl;
cout << "出版年份: " << book.year << endl << endl;
}
}
};
int main() {
BookManager manager;
// 添加一些示例书籍
manager.addBook("The Great Gatsby", "F. Scott Fitzgerald", 1925);
manager.addBook("To Kill a Mockingbird", "Harper Lee", 1960);
manager.addBook("1984", "George Orwell", 1949);
// 显示所有书籍
manager.displayAllBooks();
// 查找书籍
manager.findBook("To Kill a Mockingbird");
// 删除一本书籍
manager.removeBook("1984");
// 再次显示所有书籍
manager.displayAllBooks();
return 0;
}
这段代码创建了一个简单的书籍管理系统,其中包含一个 Book 结构体表示书籍的属性,以及一个 BookManager 类用于管理书籍。主函数演示了如何使用该系统来添加、删除、查找和显示书籍信息。