1.实验目标:
图书信息管理系统。
2.实验要求:
使用链式存储实现,基本功能如下(不限于此):
(1)读取文件中的图书信息。
(2)输出图书信息。
(3)图书的增、删、改、查。
(4)有方便合理的菜单选择。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// 图书类
class Book {
private:
string title;
string author;
int year;
public:
Book(const string& t, const string& a, int y) : title(t), author(a), year(y) {}
void display() const {
cout << "书名:" << title << endl;
cout << "作者:" << author << endl;
cout << "出版年份:" << year << endl;
cout << endl;
}
string getTitle() const {
return title;
}
};
// 链表节点类
class Node {
public:
Book book;
Node* next;
Node(const Book& b) : book(b), next(NULL) {}
};
// 图书管理系统类
class Library {
private:
Node* head;
public:
Library() : head(NULL) {}
~Library() {
// 释放链表内存
Node* current = head;
while (current != NULL) {
Node* next = current->next;
delete current;
current = next;
}
}
// 从文件中读取图书信息
// 输出图书信息
void displayBooks() const {
if (head == NULL) {
cout << "图书馆为空" << endl;
} else {
Node* current = head;
while (current != NULL) {
current->book.display();
current = current->next;
}
}
}
// 添加图书
void addBook(const Book& book) {
Node* newNode = new Node(book);
if (head == NULL) {
head = newNode;
} else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
cout << "成功添加图书" << endl;
}
// 删除图书
void removeBook(const string& title) {
if (head == NULL) {
cout << "图书馆为空" << endl;
} else if (head->book.getTitle() == title) {
Node* temp = head;
head = head->next;
delete temp;
cout << "成功删除图书" << endl;
} else {
Node* current = head;
while (current->next != NULL) {
if (current->next->book.getTitle() == title) {
Node* temp = current->next;
current->next = current->next->next;
delete temp;
cout << "成功删除图书" << endl;
return;
}
current = current->next;
}
cout << "未找到指定图书" << endl;
}
}
// 查找图书
void searchBook(const string& title) const {
if (head == NULL) {
cout << "图书馆为空" << endl;
} else {
Node* current = head;
while (current != NULL) {
if (current->book.getTitle() == title) {
cout << "找到指定图书:" << endl;
current->book.display();
return;
}
current = current->next;
}
cout << "未找到指定图书" << endl;
}
}
};
int main() {
Library library;
while (true) {
cout << endl << "图书管理系统菜单:" << endl;
cout << "1. 显示图书信息" << endl;
cout << "2. 添加图书" << endl;
cout << "3. 删除图书" << endl;
cout << "4. 查找图书" << endl;
cout << "0. 退出系统" << endl;
int choice;
cout << "请输入功能选项:";
cin >> choice;
if (choice == 0) {
cout << "感谢使用图书管理系统,再见!" << endl;
break;
}
string title, author;
int year;
switch (choice) {
case 1:
library.displayBooks();
break;
case 2:
cout << "请输入图书信息:" << endl;
cout << "书名:";
cin.ignore();
getline(cin, title);
cout << "作者:";
getline(cin, author);
cout << "出版年份:";
cin >> year;
library.addBook(Book(title, author, year));
break;
case 3:
cout << "请输入要删除的图书书名:";
cin.ignore();
getline(cin, title);
library.removeBook(title);
break;
case 4:
cout << "请输入要查找的图书书名:";
cin.ignore();
getline(cin, title);
library.searchBook(title);
break;
default:
cout << "无效的选项" << endl;
break;
}
}
return 0;
}