超市信息管理系统(C++)
时间: 2023-07-10 13:34:50 浏览: 91
以下是一个简单的超市信息管理系统的 C++ 代码示例,实现了添加商品、查看商品、修改商品和删除商品功能:
```c++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct Product {
string name;
double price;
int stock;
};
vector<Product> products;
void addProduct() {
Product product;
cout << "Enter product name: ";
cin >> product.name;
cout << "Enter product price: ";
cin >> product.price;
cout << "Enter product stock: ";
cin >> product.stock;
products.push_back(product);
cout << "Product added successfully!" << endl;
}
void viewProducts() {
if (products.empty()) {
cout << "No products found!" << endl;
return;
}
cout << "Product list:" << endl;
for (const auto& product : products) {
cout << product.name << " - $" << product.price << " - " << product.stock << " in stock" << endl;
}
}
void editProduct() {
if (products.empty()) {
cout << "No products found!" << endl;
return;
}
cout << "Enter the name of the product you want to edit: ";
string name;
cin >> name;
for (auto& product : products) {
if (product.name == name) {
cout << "Enter new product name (leave blank to keep current name): ";
string new_name;
cin.ignore();
getline(cin, new_name);
if (!new_name.empty()) {
product.name = new_name;
}
cout << "Enter new product price (leave blank to keep current price): ";
string new_price_str;
getline(cin, new_price_str);
if (!new_price_str.empty()) {
product.price = stod(new_price_str);
}
cout << "Enter new product stock (leave blank to keep current stock): ";
string new_stock_str;
getline(cin, new_stock_str);
if (!new_stock_str.empty()) {
product.stock = stoi(new_stock_str);
}
cout << "Product updated successfully!" << endl;
return;
}
}
cout << "Product not found!" << endl;
}
void deleteProduct() {
if (products.empty()) {
cout << "No products found!" << endl;
return;
}
cout << "Enter the name of the product you want to delete: ";
string name;
cin >> name;
for (auto it = products.begin(); it != products.end(); ++it) {
if (it->name == name) {
products.erase(it);
cout << "Product deleted successfully!" << endl;
return;
}
}
cout << "Product not found!" << endl;
}
int main() {
while (true) {
cout << "Supermarket Information Management System" << endl;
cout << "1. Add product" << endl;
cout << "2. View products" << endl;
cout << "3. Edit product" << endl;
cout << "4. Delete product" << endl;
cout << "5. Exit" << endl;
cout << "Enter your choice: ";
int choice;
cin >> choice;
switch (choice) {
case 1:
addProduct();
break;
case 2:
viewProducts();
break;
case 3:
editProduct();
break;
case 4:
deleteProduct();
break;
case 5:
return 0;
default:
cout << "Invalid choice!" << endl;
}
cout << endl;
}
return 0;
}
```
该程序使用了一个 `Product` 结构体来表示每个商品的信息,然后使用了 `vector` 来存储所有商品。用户可以选择添加商品、查看商品、修改商品或删除商品。添加商品时,程序会要求用户输入商品名称、价格和库存,然后将商品添加到 `vector` 中。查看商品时,程序会遍历 `vector` 并输出所有商品的信息。修改商品时,程序会要求用户输入商品名称,然后查找该商品并允许用户修改其名称、价格和库存。删除商品时,程序会要求用户输入商品名称,然后查找该商品并从 `vector` 中删除它。