c++设计一个超市管理系统代码
时间: 2023-11-27 22:53:17 浏览: 175
以下是一个简单的超市管理系统的C++代码,实现了基本的商品管理和销售功能。
```c++
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>
using namespace std;
// 商品结构体
struct Commodity {
string name; // 商品名称
double price; // 商品单价
int inventory; // 商品库存
// 构造函数
Commodity(string n, double p, int i) : name(n), price(p), inventory(i) {}
};
// 超市类
class Supermarket {
private:
vector<Commodity> commodities; // 商品列表
public:
// 添加商品
void addCommodity(string name, double price, int inventory) {
commodities.emplace_back(name, price, inventory);
cout << "商品添加成功!" << endl;
}
// 显示商品列表
void showCommodityList() {
cout << left << setw(10) << "编号"
<< left << setw(20) << "商品名称"
<< left << setw(10) << "单价"
<< left << setw(10) << "库存" << endl;
for (int i = 0; i < commodities.size(); i++) {
cout << left << setw(10) << i + 1
<< left << setw(20) << commodities[i].name
<< left << setw(10) << commodities[i].price
<< left << setw(10) << commodities[i].inventory << endl;
}
}
// 销售商品
void sellCommodity(int index, int quantity) {
if (index < 1 || index > commodities.size()) {
cout << "商品不存在!" << endl;
return;
}
Commodity& commodity = commodities[index - 1];
if (commodity.inventory < quantity) {
cout << "库存不足!" << endl;
return;
}
commodity.inventory -= quantity;
double totalPrice = commodity.price * quantity;
cout << "商品销售成功!总价:" << totalPrice << endl;
}
};
int main() {
Supermarket market;
int choice;
while (true) {
cout << "超市管理系统" << endl;
cout << "1. 添加商品" << endl;
cout << "2. 显示商品列表" << endl;
cout << "3. 销售商品" << endl;
cout << "4. 退出" << endl;
cout << "请选择操作:";
cin >> choice;
switch (choice) {
case 1: {
string name;
double price;
int inventory;
cout << "请输入商品名称:";
cin >> name;
cout << "请输入商品单价:";
cin >> price;
cout << "请输入商品库存:";
cin >> inventory;
market.addCommodity(name, price, inventory);
break;
}
case 2: {
market.showCommodityList();
break;
}
case 3: {
int index;
int quantity;
cout << "请输入要销售的商品编号:";
cin >> index;
cout << "请输入销售数量:";
cin >> quantity;
market.sellCommodity(index, quantity);
break;
}
case 4: {
return 0;
}
default: {
cout << "无效操作!" << endl;
}
}
}
}
```
该代码使用了结构体存储商品信息,使用vector容器存储商品列表,实现了商品添加、显示商品列表和销售商品等基本功能。
阅读全文