1.主要功能
能够添加菜品
能够点菜
能够查看一点菜品
能够保存菜单
2.代码区域
#include <iostream>
#include <fstream>
#include <map>
#include <string>
#include <vector>
using namespace std;
// 定义菜单数据结构,使用 map 类型
map<string, int> menu;
// 定义已点菜品数据结构,使用 vector 类型
vector<string> ordered_dishes;
// 显示当前菜单
void show_menu() {
cout << "当前菜单:" << endl;
int i = 0;
system("cls");
for (auto it = menu.cbegin(); it != menu.cend(); ++it) {
cout << it->first << ": " << it->second << "元" << endl;
}
system("pause");
}
// 添加新的菜品到菜单中
void add_dish() {
string dish_name;
int price;
char i=0;
system("cls");
cout << "输入y继续,否则退出" << endl;
A: cout << "请输入新的菜品名称:";
cin >> dish_name;
cout << "请输入新的菜品价格(元):";
cin >> price;
menu[dish_name] = price;
cout << "已成功添加新的菜品:" << dish_name << endl;
cout << "请选择y是继续,其他退出" << endl;
cin >> i;
if (i == 'y')
{
goto A;
}
else
{ }
}
// 保存菜单到文件
void save_menu(string file_path) {
ofstream outfile(file_path);
if (outfile.is_open()) {
for (auto it = menu.cbegin(); it != menu.cend(); ++it) {
outfile << it->first << "," << it->second << endl;
}
outfile.close();
cout << "已成功保存菜单到文件:" << file_path << endl;
}
else {
cout << "无法打开文件:" << file_path << endl;
}
}
// 从文件加载菜单
void load_menu(string file_path) {
ifstream infile(file_path);
if (infile.is_open()) {
menu.clear();
string line;
while (getline(infile, line)) {
size_t pos = line.find(",");
if (pos != string::npos) {
string dish_name = line.substr(0, pos);
int price = stoi(line.substr(pos + 1));
menu[dish_name] = price;
}
}
infile.close();
cout << "已成功加载菜单:" << file_path << endl;
}
else {
cout << "无法打开文件:" << file_path << endl;
}
}
// 点菜
void order_dish() {
show_menu();
string dish_name;
b: cout << "请输入要点的菜品名称:";
cin >> dish_name;
if (dish_name == "ok")
{
}
else
{
if (menu.count(dish_name) > 0) {
ordered_dishes.push_back(dish_name);
cout << "已成功点菜:" << dish_name << endl;
}
else {
cout << "菜单中不存在该菜品。" << endl;
}
goto b;
}
}
// 显示已点菜品
void show_ordered_dishes() {
cout << "已点菜品:" << endl;
for (const string& dish : ordered_dishes) {
cout << dish << endl;
}
system("pause");
}
int main() {
string file_path = "menu.txt";
// 加载菜单
load_menu(file_path);
while (true) {
cout << "请选择操作:" << endl;
cout << "1. 查看菜单" << endl;
cout << "2. 添加菜品" << endl;
cout << "3. 点菜" << endl;
cout << "4. 查看已点菜品" << endl;
cout << "5. 保存菜单并退出" << endl;
string choice;
cin >> choice;
if (choice == "1") {
show_menu();
}
else if (choice == "2") {
add_dish();
}
else if (choice == "3") {
order_dish();
}
else if (choice == "4") {
show_ordered_dishes();
}
else if (choice == "5") {
save_menu(file_path);
break;
}
else {
cout << "无效选项,请重新输入。" << endl;
}
}
return 0;
}