#include using namespace std; #include "sqlist.h" // 顺序表 // 图书信息 struct Book { int id; // 编号 string title; // 标题 string author; // 作者 float price; // 价格 }; // 所有书的列表 SqList books; int get_command(); // 读取命令 void DoAddBook(); // 添加图书 void DoFindBook(); // 查找图书 void DoDeleteBook(); // 删除图书 void DoPrintBook(); // 打印图书 int main() { bool finish = false; InitList(books); while (!finish) { switch (get_command()) { case 1: // Add book DoAddBook(); break; case 2: // Find book DoFindBook(); break; case 3: // Delete book DoDeleteBook(); break; case 4: // Print DoPrintBook(); break; case 0: // Exit finish = true; break; default: // no command cout << "Error command." << endl; } } DestroyList(books); return 0; } // 读取命令 int get_command() { int cmd; cout << "Commands: (1) Add, (2) Find, (3) Delete, (4) Print, (0) Exit\n"; cout << "Enter your choice (0-4): "; cin >> cmd; return cmd; } // 输入一本书的信息 void read(Book& b) { cout << "ID : "; cin >> b.id; cin.ignore(1024, '\n'); // skip rest chars of the line cout << "TITLE : "; getline(cin, b.title); cout << "AUTHOR: "; getline(cin, b.author); cout << "PRICE : "; cin >> b.price; } // 打印一本书的信息 void print(const Book& b) { cout << "Book { id: " << b.id << "," << " title:\"" << b.title << "\"," << " author: \"" << b.author << "\"," << " price: " << b.price << " }" << endl; } // 根据 id 查找图书 // 若找到,返回元素的位序,找不到时返回 0 int find(int id) { for (int i = 1; i <= books.length; i++) { if (id == books.elem[i].id){ return i; } } return 0; // not found } // 添加图书 void DoAddBook() { Book e; read(e); books.elem[books.length + 1] = e; books.length++; print(e); cout << "Added" << endl; } // 查找图书 void DoFindBook() { int id; cout << "Enter book ID: "; cin >> id; Book e; if (find(id) == 0) cout << "Not found" << endl; else { e = books.elem[find(id)]; print(e); cout << "Found" << endl; } } // 删除图书 void DoDeleteBook() { int id; cout << "Enter book ID: "; cin >> id; Book e; int c = find(id); if (find(id) == 0) cout << "Not found" << endl; else { e = books.elem[c]; print(e); for (int i = c; i < books.length; i++) { books.elem[i] = books.elem[i + 1]; } --books.length; cout << "Deleted" << endl; } } // 打印图书 void DoPrintBook() { int flag = 0; for (int i = 0; i < books.length; i++) { Book e; e = books.elem[i + 1]; print(e); flag++; } cout << "Total: "; cout << flag; cout << " books" << endl; }