基于控制台的购书系统代码
时间: 2023-08-08 13:14:02 浏览: 161
以下是一个基于控制台的购书系统代码的示例,使用C++实现:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Book {
string title;
string author;
double price;
int quantity;
};
vector<Book> books;
void addBook() {
Book book;
cout << "Enter book title: ";
getline(cin, book.title);
cout << "Enter author name: ";
getline(cin, book.author);
cout << "Enter book price: ";
cin >> book.price;
cout << "Enter quantity: ";
cin >> book.quantity;
cin.ignore(); // ignore newline character
books.push_back(book);
cout << "Book added successfully!\n";
}
void listBooks() {
for (int i = 0; i < books.size(); i++) {
cout << "Title: " << books[i].title << endl;
cout << "Author: " << books[i].author << endl;
cout << "Price: " << books[i].price << endl;
cout << "Quantity: " << books[i].quantity << endl << endl;
}
}
void purchaseBook() {
string title;
bool found = false;
cout << "Enter book title to purchase: ";
getline(cin, title);
for (int i = 0; i < books.size(); i++) {
if (books[i].title == title) {
found = true;
int quantity;
cout << "Enter quantity to purchase: ";
cin >> quantity;
if (quantity > books[i].quantity) {
cout << "Insufficient stock!\n";
} else {
books[i].quantity -= quantity;
double total = quantity * books[i].price;
cout << "Purchase successful. Total cost: " << total << endl;
}
break;
}
}
if (!found) {
cout << "Book not found!\n";
}
cin.ignore(); // ignore newline character
}
int main() {
int choice;
do {
cout << "1. Add book\n";
cout << "2. List all books\n";
cout << "3. Purchase book\n";
cout << "4. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // ignore newline character
switch (choice) {
case 1:
addBook();
break;
case 2:
listBooks();
break;
case 3:
purchaseBook();
break;
case 4:
cout << "Goodbye!\n";
break;
default:
cout << "Invalid choice!\n";
break;
}
} while (choice != 4);
return 0;
}
```
这个示例中,我们定义了一个`Book`结构体来表示一本书的信息。`addBook()`函数允许用户添加一本新书,`listBooks()`函数列出库存中的所有书籍,`purchaseBook()`函数允许用户购买一本书。主函数则通过一个循环来处理用户输入的选项。