C++库存管理系统通过定义Item类和InventoryManager类,使用std::map存储商品信息,实现添加、删除、更新、查询及文件持久化功能,支持CSV格式数据读写,确保程序重启后数据不丢失。

在C++中实现库存管理功能,核心在于合理地设计数据结构来表示商品,并封装一系列操作(如添加、移除、更新、查询)到一个管理类中。这通常涉及到定义一个商品类(
Item
std::map
std::unordered_map
要构建一个实用的C++库存管理系统,我的思路通常是先从最基础的“物”——也就是库存中的商品——开始定义。一个
Item
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <fstream>
#include <limits> // For numeric_limits
// 定义商品结构
struct Item {
std::string id;
std::string name;
int quantity;
double price;
// 默认构造函数
Item() : id(""), name(""), quantity(0), price(0.0) {}
Item(std::string _id, std::string _name, int _quantity, double _price)
: id(std::move(_id)), name(std::move(_name)), quantity(_quantity), price(_price) {}
// 用于输出商品信息
void display() const {
std::cout << "ID: " << id
<< ", Name: " << name
<< ", Quantity: " << quantity
<< ", Price: $" << std::fixed << std::setprecision(2) << price << std::endl;
}
};
// 库存管理类
class InventoryManager {
private:
std::map<std::string, Item> inventory; // 使用map以ID作为键,便于查找和更新
const std::string dataFilePath = "inventory.txt"; // 数据存储文件
public:
InventoryManager() {
loadInventory(); // 构造时加载库存
}
~InventoryManager() {
saveInventory(); // 析构时保存库存
}
// 添加商品
void addItem(const Item& item) {
if (inventory.count(item.id)) {
std::cout << "Error: Item with ID " << item.id << " already exists. Use update to change quantity." << std::endl;
return;
}
inventory[item.id] = item;
std::cout << "Item '" << item.name << "' added successfully." << std::endl;
}
// 移除商品
void removeItem(const std::string& itemId) {
if (inventory.erase(itemId)) {
std::cout << "Item with ID " << itemId << " removed successfully." << std::endl;
} else {
std::cout << "Error: Item with ID " << itemId << " not found." << std::endl;
}
}
// 更新商品数量
void updateItemQuantity(const std::string& itemId, int change) {
auto it = inventory.find(itemId);
if (it != inventory.end()) {
if (it->second.quantity + change >= 0) {
it->second.quantity += change;
std::cout << "Quantity for item '" << it->second.name << "' updated to " << it->second.quantity << "." << std::endl;
} else {
std::cout << "Error: Cannot reduce quantity below zero for item '" << it->second.name << "'." << std::endl;
}
} else {
std::cout << "Error: Item with ID " << itemId << " not found." << std::endl;
}
}
// 查找商品
Item* findItem(const std::string& itemId) {
auto it = inventory.find(itemId);
if (it != inventory.end()) {
return &(it->second);
}
return nullptr; // 未找到返回空指针
}
// 显示所有商品
void displayAllItems() const {
if (inventory.empty()) {
std::cout << "Inventory is empty." << std::endl;
return;
}
std::cout << "\n--- Current Inventory ---" << std::endl;
for (const auto& pair : inventory) {
pair.second.display();
}
std::cout << "-------------------------" << std::endl;
}
// 保存库存到文件
void saveInventory() const {
std::ofstream outFile(dataFilePath);
if (!outFile.is_open()) {
std::cerr << "Error: Could not open file " << dataFilePath << " for writing." << std::endl;
return;
}
for (const auto& pair : inventory) {
outFile << pair.second.id << ","
<< pair.second.name << ","
<< pair.second.quantity << ","
<< pair.second.price << std::endl;
}
outFile.close();
std::cout << "Inventory saved to " << dataFilePath << std::endl;
}
// 从文件加载库存
void loadInventory() {
std::ifstream inFile(dataFilePath);
if (!inFile.is_open()) {
std::cerr << "Warning: Could not open file " << dataFilePath << " for reading. Starting with empty inventory." << std::endl;
return;
}
inventory.clear(); // 清空当前内存中的库存
std::string line;
while (std::getline(inFile, line)) {
std::string id, name, quantityStr, priceStr;
size_t pos1 = line.find(',');
size_t pos2 = line.find(',', pos1 + 1);
size_t pos3 = line.find(',', pos2 + 1);
if (pos1 == std::string::npos || pos2 == std::string::npos || pos3 == std::string::npos) {
std::cerr << "Warning: Malformed line in inventory file: " << line << std::endl;
continue;
}
id = line.substr(0, pos1);
name = line.substr(pos1 + 1, pos2 - (pos1 + 1));
quantityStr = line.substr(pos2 + 1, pos3 - (pos2 + 1));
priceStr = line.substr(pos3 + 1);
try {
int quantity = std::stoi(quantityStr);
double price = std::stod(priceStr);
inventory[id] = Item(id, name, quantity, price);
} catch (const std::exception& e) {
std::cerr << "Error parsing line: " << line << " - " << e.what() << std::endl;
}
}
inFile.close();
std::cout << "Inventory loaded from " << dataFilePath << std::endl;
}
};
// 简单的用户界面
void showMenu() {
std::cout << "\n--- Inventory Management System ---" << std::endl;
std::cout << "1. Add Item" << std::endl;
std::cout << "2. Remove Item" << std::endl;
std::cout << "3. Update Item Quantity" << std::endl;
std::cout << "4. Display All Items" << std::endl;
std::cout << "5. Find Item" << std::endl;
std::cout << "6. Save Inventory" << std::endl;
std::cout << "7. Load Inventory" << std::endl;
std::cout << "0. Exit" << std::endl;
std::cout << "Enter your choice: ";
}
int main() {
InventoryManager manager;
int choice;
std::string id, name;
int quantity;
double price;
do {
showMenu();
std::cin >> choice;
// 清除输入缓冲区,防止后续getline读取到换行符
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
switch (choice) {
case 1: {
std::cout << "Enter Item ID: ";
std::getline(std::cin, id);
std::cout << "Enter Item Name: ";
std::getline(std::cin, name);
std::cout << "Enter Quantity: ";
std::cin >> quantity;
std::cout << "Enter Price: ";
std::cin >> price;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // 再次清理
manager.addItem(Item(id, name, quantity, price));
break;
}
case 2: {
std::cout << "Enter Item ID to remove: ";
std::getline(std::cin, id);
manager.removeItem(id);
break;
}
case 3: {
std::cout << "Enter Item ID to update: ";
std::getline(std::cin, id);
std::cout << "Enter quantity change (e.g., 5 for add, -3 for remove): ";
std::cin >> quantity;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
manager.updateItemQuantity(id, quantity);
break;
}
case 4: {
manager.displayAllItems();
break;
}
case 5: {
std::cout << "Enter Item ID to find: ";
std::getline(std::cin, id);
Item* foundItem = manager.findItem(id);
if (foundItem) {
std::cout << "Found Item: ";
foundItem->display();
} else {
std::cout << "Item with ID " << id << " not found." << std::endl;
}
break;
}
case 6: {
manager.saveInventory();
break;
}
case 7: {
manager.loadInventory();
break;
}
case 0: {
std::cout << "Exiting system. Goodbye!" << std::endl;
break;
}
default: {
std::cout << "Invalid choice. Please try again." << std::endl;
break;
}
}
} while (choice != 0);
return 0;
}这段代码提供了一个基本的命令行交互式库存管理系统。
Item
InventoryManager
std::map
在C++中设计库存管理系统时,选择合适的数据结构来存储商品信息是至关重要的一步,它直接影响到系统的性能和可维护性。我个人在做这类系统时,通常会根据核心操作(如查找、添加、删除、遍历)的频率和性能要求来权衡。
立即学习“C++免费学习笔记(深入)”;
首先,
std::vector<Item>
vector
std::list<Item>
vector
list
我更倾向于使用关联容器,特别是
std::map<std::string, Item>
std::unordered_map<std::string, Item>
std::map
std::map
而
std::unordered_map
std::string
Modoer 是一款以本地分享,多功能的点评网站管理系统。采用 PHP+MYSQL 开发设计,开放全部源代码。因具有非凡的访问速度和卓越的负载能力而深受国内外朋友的喜爱,不局限于商铺类点评,真正实现了多类型的点评,可以让您的网站点评任何事与物,同时增加产品模块,也更好的网站产品在网站上展示。Modoer点评系统 2.5 Build 20110710更新列表1.同步 旗舰版系统框架2.增加 限制图片
0
总结一下我的经验:
std::vector
std::map
std::unordered_map
在上面的示例代码中,我选择了
std::map
std::unordered_map
数据持久化是任何管理系统不可或缺的一部分,它确保了程序关闭后数据不会丢失。在C++中,为库存管理系统添加数据持久化功能,最常见且直接的方法就是使用文件I/O。我们可以选择不同的文件格式,每种都有其优缺点。
1. 文本文件(如CSV格式): 这是最简单、最直观的实现方式。每一行代表一个商品,商品的各个属性用逗号(或其他分隔符)隔开。
std::map
Item
id,name,quantity,price
std::getline
std::string::find
std::string::substr
stringstream
Item
std::map
在示例代码中,我正是采用了这种CSV风格的文本文件方式。它足够简单,能够快速实现基本功能,并且用户可以直接打开文件查看数据。但在实际应用中,你可能需要更健壮的解析逻辑来处理分隔符冲突、空字段等问题。
2. JSON格式: JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,它比CSV更具结构化,能够更好地表示复杂的数据关系。
nlohmann/json
Item
Item
如果你的库存数据结构未来可能变得复杂,或者需要与其他系统进行数据交换,那么投入时间学习和集成一个JSON库是非常值得的。
3. 二进制文件: 直接将C++对象的数据按其内存布局写入文件。
Item
ofstream::write
Item
ifstream::read
Item
对于库存管理这种需要频繁更新和持久化的场景,我通常会避免直接使用二进制文件,除非有非常严格的性能或存储空间要求,并且能够接受
以上就是C++如何实现库存管理功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号