c++实现控制台图书管理系统
时间: 2023-08-10 13:09:49 浏览: 48
好的,下面是一个简单的控制台图书管理系统的C++实现:
```cpp
#include <iostream>
#include <cstring>
using namespace std;
const int MAX_BOOKS = 100;
class Book {
private:
string title;
string author;
int year;
public:
Book(string title = "", string author = "", int year = 0) {
this->title = title;
this->author = author;
this->year = year;
}
string getTitle() {
return title;
}
string getAuthor() {
return author;
}
int getYear() {
return year;
}
};
class Library {
private:
Book books[MAX_BOOKS];
int numBooks;
public:
Library() {
numBooks = 0;
}
void addBook(string title, string author, int year) {
if (numBooks < MAX_BOOKS) {
books[numBooks++] = Book(title, author, year);
cout << "Book added successfully!" << endl;
}
else {
cout << "Library is full!" << endl;
}
}
void listBooks() {
if (numBooks == 0) {
cout << "Library is empty!" << endl;
}
else {
cout << "Library contents:" << endl;
for (int i = 0; i < numBooks; i++) {
cout << books[i].getTitle() << " by " << books[i].getAuthor() << " (" << books[i].getYear() << ")" << endl;
}
}
}
};
int main() {
Library library;
int choice;
string title, author;
int year;
do {
cout << "Select an option:" << endl;
cout << "1. Add book" << endl;
cout << "2. List books" << endl;
cout << "3. Quit" << endl;
cin >> choice;
switch (choice) {
case 1:
cout << "Enter title, author, and year:" << endl;
cin >> title >> author >> year;
library.addBook(title, author, year);
break;
case 2:
library.listBooks();
break;
case 3:
break;
default:
cout << "Invalid option!" << endl;
break;
}
} while (choice != 3);
return 0;
}
```
这个系统包含两个类:`Book`和`Library`。`Book`类表示一本书,包含标题、作者和年份等信息;`Library`类表示整个图书馆,包含一个`Book`类型的数组和一些基本的操作,如添加书籍和列出所有书籍。
在主函数中,我们使用一个循环来不断读取用户输入的选项,并执行相应的操作。用户可以选择添加一本书籍、列出所有书籍或退出系统。