功能 代码在效果图后面
1.添加物品 2.删除物品 3.更新物品数量 4.查询物品 5.列出所有物品 6.保存并退出
注意事项:退出要输入“6”退出才能保存数据,不要直接按X关掉窗口(不会保存数据)。
效果图
源代码
编译时在连接器命令行加入以下数据
-std=c++11
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>struct Item {int id;std::string name;int quantity;std::string type;
};class WarehouseManagement {
public:WarehouseManagement(const std::string& filename) : filename(filename) {loadFromFile();}bool authenticate(const std::string& username, const std::string& password) {return username == "root" && password == "123";}void addItem(const Item& item) {items.push_back(item);saveToFile();}void removeItem(int id) {auto it = std::remove_if(items.begin(), items.end(), [id](const Item& item) {return item.id == id;});items.erase(it, items.end());saveToFile();}void updateItemQuantity(int id, int quantity) {for (auto& item : items) {if (item.id == id) {item.quantity = quantity;saveToFile();return;}}}Item* queryItem(int id) {for (auto& item : items) {if (item.id == id) {return &item;}}return nullptr;}void printItems() {for (const auto& item : items) {std::cout << "ID: " << item.id << ", 名称: " << item.name<< ", 数量: " << item.quantity << ", 类型: " << item.type << '\n';}}private:std::vector<Item> items;std::string filename;void loadFromFile() {std::ifstream file(filename);if (!file.is_open()) return;Item item;while (file >> item.id >> item.name >> item.quantity >> item.type) {items.push_back(item);}file.close();}void saveToFile() {std::ofstream file(filename);if (!file.is_open()) return;for (const auto& item : items) {file << item.id << ' ' << item.name << ' ' << item.quantity << ' ' << item.type << '\n';}file.close();}
};int main() {WarehouseManagement wm("warehouse.txt");std::string username, password;std::cout << "请输入用户名: ";std::cin >> username;std::cout << "请输入密码: ";std::cin >> password;if (!wm.authenticate(username, password)) {std::cout << "无效的用户名或密码。\n";return 1;}int choice;do {std::cout << "1. 添加物品\n2. 删除物品\n3. 更新物品数量\n4. 查询物品\n5. 列出所有物品\n6. 退出\n";std::cout << "请输入您的选择: ";std::cin >> choice;switch (choice) {case 1: {Item item;std::cout << "请输入物品ID: ";std::cin >> item.id;std::cout << "请输入物品名称: ";std::cin >> item.name;std::cout << "请输入物品数量: ";std::cin >> item.quantity;std::cout << "请输入物品类型: ";std::cin >> item.type;wm.addItem(item);break;}case 2: {int id;std::cout << "请输入要删除的物品ID: ";std::cin >> id;wm.removeItem(id);break;}case 3: {int id, quantity;std::cout << "请输入要更新的物品ID: ";std::cin >> id;std::cout << "请输入新的数量: ";std::cin >> quantity;wm.updateItemQuantity(id, quantity);break;}case 4: {int id;std::cout << "请输入要查询的物品ID: ";std::cin >> id;Item* item = wm.queryItem(id);if (item) {std::cout << "ID: " << item->id << ", 名称: " << item->name<< ", 数量: " << item->quantity << ", 类型: " << item->type << '\n';} else {std::cout << "物品未找到。\n";}break;}case 5:wm.printItems();break;case 6:break;default:std::cout << "无效的选择。请再试一次。\n";break;}} while (choice != 6);return 0;
}