gpt4 book ai didi

c++ - c++中菜单和子菜单的优化

转载 作者:太空宇宙 更新时间:2023-11-04 14:30:01 24 4
gpt4 key购买 nike

我创建了一个包含四个选项的菜单,当您选择其中一个选项时,系统会将您重定向到另一个子菜单,例如,其中有两个选项,之后程序将执行它们必须执行的操作。我成功地做到了这一点,但我的问题是我想对此进行优化,以便用户插入的所有可能性都将是一个相同的函数 Menu_select() 以便正确编码。例如,如果用户选择选项 2,然后选择选项 1,所有这些都将在 Menu_select() 下进行管理,而不是在每个子菜单中如果选择 (x) do x 并且如果选择 (y) do ( y)。总而言之,我想将用户可以选择的所有选项集中在同一个功能下。

这是我的代码:

int Shop::Menu_select(int choose)
{
switch (choose)
{
case 1:
break;
case 2:
Menu_Video();
break;
case 3:
break;
case 4:
exit(EXIT_FAILURE);
break;
default:
break;
}
}
void Shop::Menu()
{
int choose = 0;
cout << "Rony Dvd Rental Shop !" << endl;
cout << "1.Customer" << endl;
cout << "2.Dvd" << endl;
cout << "3.Rental" << endl;
cout << "4.Exit" << endl;

cout << endl << "Choose an option: ";
cin >> choose;

Menu_select(choose);
}
void Shop::Menu_Video()
{
int choose = 0;

system("cls");
cout << "1.Add Dvd to the store " << endl;
cout << "2.Delete Dvd from the store " << endl;

cout << endl << "Choose an option: ";
cin >> choose;

if (choose == 1)
{
system("cls");
cout << "You want to add Dvd to the store" << endl;
}
else
{
system("cls");
cout << "You want to delete Dvd from the store" << endl;
}


}

谢谢!

最佳答案

你可以按照下面的例子进行优化

#include <iostream>
#include <string>

using namespace std;

int menu(string mArray[],int menuLength){
int choosen = 0;
for (int i=0;i<menuLength;i++)
cout << mArray[i] << endl;
cout << "Enter your choice -->" ;
cin >> choosen;
return choosen;
}

void menu_select(int select){
switch(select){
case 1:
// for menu
cout << "menu opt-1" << endl;
break;
case 2:
cout << "menu opt-2" << endl;
break;
case 3:
cout << "menu opt-3" << endl;
break;
case 4:
cout << "menu opt-4" << endl;
break;
case 5:
// for sub-menu
cout << "sub-menu opt-1" << endl;
break;
case 6:
// for sub-menu
cout << "sub-menu opt-2" << endl;
break;
}
}

int main(){

string menu1[] = {"1.Option1","2.Option2","3.Option3","4.Option4"};
string menu2[] = {"1.Option-1","2.Option-2"};

int ch1=0,ch2=0;
ch1 = menu(menu1,4);
cout << "You entered:" << ch1 << endl;

menu_select(ch1);
ch2=menu(menu2,2);
//sub-menu with options
cout << "You entered:" << ch2 << endl;

//check ch2 not zero
menu_select(ch2+4); // if main menu has four options
}

关于c++ - c++中菜单和子菜单的优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41676953/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com