2017-01-16 36 views
0

我創建了一個包含四個選項的菜單,當你選擇其中一個選項時,它會將你重定向到另一個子菜單,例如有兩個選項,然後程序將執行它們的操作去做。我成功做到這一點,但我的問題是我想優化,以便用戶插入的所有可能性將是一個相同的函數Menu_select()爲了正確編碼。例如,如果用戶選擇了選項2,則在選項1之後,所有這些都將在Menu_select()下管理,而不是在每個子菜單中,如果選擇(x)執行x並且選擇(y)執行Y)。爲了達到目的,我想在相同的功能下彙集用戶可以選擇的所有選項。菜單和子菜單在C++中的優化

這是我的代碼:

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


} 

謝謝!

回答

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 
}