在c ++中优化菜单和子菜单

时间:2017-01-16 12:56:59

标签: c++ menu

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


}

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以按照以下示例进行优化

#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
}

答案 1 :(得分:-1)

您应该使用QT或Win32(仅限Windows)库执行此操作。这将极大地增加功能,并使您的最终产品看起来更好。

这里有一些文档。 用于基本窗口 https://msdn.microsoft.com/en-us/library/bb384843.aspx 用于菜单选择 https://msdn.microsoft.com/en-us/library/windows/desktop/ms646977(v=vs.85).aspx