写一个图书管理系统c++代码
时间: 2023-11-04 22:05:02 浏览: 125
以下是一个简单的图书管理系统的 C++ 代码,实现了基本的图书添加、查询、修改和删除功能:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// 图书类
class Book {
public:
string name; // 书名
string author; // 作者
string publisher; // 出版社
int year; // 出版年份
int pages; // 页数
Book() {}
Book(string n, string a, string p, int y, int pg) {
name = n;
author = a;
publisher = p;
year = y;
pages = pg;
}
};
// 图书管理系统类
class Library {
private:
vector<Book> books; // 图书列表
public:
// 添加图书
void addBook() {
string name, author, publisher;
int year, pages;
cout << "请输入书名:";
cin >> name;
cout << "请输入作者:";
cin >> author;
cout << "请输入出版社:";
cin >> publisher;
cout << "请输入出版年份:";
cin >> year;
cout << "请输入页数:";
cin >> pages;
Book book(name, author, publisher, year, pages);
books.push_back(book);
cout << "添加成功!" << endl;
}
// 查询图书
void searchBook() {
string keyword;
cout << "请输入查询关键字:";
cin >> keyword;
vector<Book>::iterator it;
for (it = books.begin(); it != books.end(); it++) {
Book book = *it;
if (book.name.find(keyword) != string::npos || book.author.find(keyword) != string::npos || book.publisher.find(keyword) != string::npos) {
cout << "书名:" << book.name << endl;
cout << "作者:" << book.author << endl;
cout << "出版社:" << book.publisher << endl;
cout << "出版年份:" << book.year << endl;
cout << "页数:" << book.pages << endl;
cout << endl;
}
}
}
// 修改图书
void modifyBook() {
string name, author, publisher;
int year, pages;
cout << "请输入要修改的书名:";
cin >> name;
vector<Book>::iterator it;
for (it = books.begin(); it != books.end(); it++) {
Book& book = *it;
if (book.name == name) {
cout << "请输入新的书名:";
cin >> book.name;
cout << "请输入新的作者:";
cin >> book.author;
cout << "请输入新的出版社:";
cin >> book.publisher;
cout << "请输入新的出版年份:";
cin >> book.year;
cout << "请输入新的页数:";
cin >> book.pages;
cout << "修改成功!" << endl;
return;
}
}
cout << "未找到该书!" << endl;
}
// 删除图书
void deleteBook() {
string name;
cout << "请输入要删除的书名:";
cin >> name;
vector<Book>::iterator it;
for (it = books.begin(); it != books.end(); it++) {
Book& book = *it;
if (book.name == name) {
books.erase(it);
cout << "删除成功!" << endl;
return;
}
}
cout << "未找到该书!" << endl;
}
};
int main() {
Library lib;
int choice;
while (true) {
cout << "请选择操作:" << endl;
cout << "1.添加图书" << endl;
cout << "2.查询图书" << endl;
cout << "3.修改图书" << endl;
cout << "4.删除图书" << endl;
cout << "5.退出系统" << endl;
cout << "请选择:";
cin >> choice;
switch (choice) {
case 1:
lib.addBook();
break;
case 2:
lib.searchBook();
break;
case 3:
lib.modifyBook();
break;
case 4:
lib.deleteBook();
break;
case 5:
cout << "谢谢使用!" << endl;
return 0;
default:
cout << "无效操作!" << endl;
}
cout << endl;
}
return 0;
}
```
注意,这只是一个非常简单的图书管理系统,没有考虑到复杂的业务逻辑和数据持久化等问题。在实际应用中,可能需要更复杂的代码和更完善的设计来满足实际需求。
阅读全文