写一个C++图书管理系统,要求具备的功能:存储书籍的各种信息如书名,书籍号,作者名;提供查找功能,按照书名或作者名查找需要的书籍;提供插入,删除,更新等功能;排序功能,能够按照作者名字将书籍排序并显示,要求程序能按照书名或书号索引,为了实用性把书籍的信息以文件的形式存储
时间: 2024-12-30 11:39:59 浏览: 4
在C++中创建一个简单的图书管理系统,我们可以设计一个包含基本数据结构的类来表示书籍,并结合文件I/O操作来实现所需的功能。首先,我们创建一个`Book`类:
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
class Book {
public:
int bookId;
std::string title;
std::string author;
// 构造函数
Book(int id, const std::string& t, const std::string& a) : bookId(id), title(t), author(a) {}
// 比较函数用于排序
bool compareAuthor(const Book& other) const {
return author < other.author;
}
};
// 文件操作函数
bool readBooksFromFile(std::vector<Book>& books);
void writeBooksToFile(const std::vector<Book>& books);
bool searchBook(const std::vector<Book>& books, const std::string& criteria, Book& result);
int main() {
std::vector<Book> library;
// 初始化数据库
if (!readBooksFromFile(library)) {
std::cout << "Error reading from file." << std::endl;
return 1;
}
while (true) {
std::cout << "\n1. Search by Title\n2. Search by Author\n3. Insert\n4. Update\n5. Delete\n6. Sort by Author\n7. Exit\n";
int choice;
std::cin >> choice;
switch (choice) {
case 1:
std::string titleToSearch;
std::cin >> titleToSearch;
Book foundBook;
if (searchBook(library, titleToSearch, foundBook)) {
std::cout << "Found: " << foundBook.title << " by " << foundBook.author << std::endl;
} else {
std::cout << "Book not found." << std::endl;
}
break;
// ...其他选项...
case 6:
std::sort(library.begin(), library.end(), &Book::compareAuthor);
for (const auto& book : library) {
std::cout << "Title: " << book.title << ", Author: " << book.author << std::endl;
}
break;
// ...更多选项...
case 7:
writeBooksToFile(library);
return 0;
}
}
return 0;
}
// 辅助函数
bool readBooksFromFile(std::vector<Book>& books) {
std::ifstream inputFile("library.txt");
if (!inputFile.is_open()) {
return false;
}
std::string line;
while (std::getline(inputFile, line)) {
std::istringstream iss(line);
int id, authorIndex;
if (!(iss >> id >> authorIndex >> line)) {
std::cerr << "Invalid data format in file." << std::endl;
return false;
}
books.push_back(Book{id, line.substr(0, line.find(',')), line.substr(line.find(',') + 1)});
}
inputFile.close();
return true;
}
void writeBooksToFile(const std::vector<Book>& books) {
std::ofstream outputFile("library.txt");
if (!outputFile.is_open()) {
std::cerr << "Failed to open output file." << std::endl;
return;
}
for (const auto& book : books) {
outputFile << book.bookId << "," << book.author << "," << book.title << '\n';
}
outputFile.close();
}
bool searchBook(const std::vector<Book>& books, const std::string& criteria, Book& result) {
// 实现具体的搜索算法...
}
```
这个示例中,我们首先定义了一个`Book`类,包含了书籍的基本信息以及比较作者名字的方法。然后有文件读写函数分别负责从文件中加载书籍和保存书籍。`main`函数处理用户交互,包括搜索、插入、更新和删除等操作。
阅读全文