2014-02-11 4 views
0

В приведенном ниже коде мне нужна помощь по альтернативам корпуса коммутатора, я имею в виду, как я могу избежать переключения и использовать другой вариант для выполнения кода.Альтернативы коммутатора

Код:

cout << " *********************Intensive Program 1***********************\n\n" << endl; 
cout << "\nHere's the menu of choices: "; 
cout << "\n1. Add a Circle.\n"; 
cout << "2. Print a Circle. \n"; 
cout << "3. Print all Cricles \n"; 
cout << "4. Exit.\n"; 
cout << "\nPlease enter your choice: "; 
cin >> choice; 
while (choice <4){ 
    switch (choice){ 

     case 1: 
      // For adding cirles to the class 
      cout << " Enter the value for the radius of the circle: "; 
      cin >> radius; 
      cout << " Enter the value for the center of the circle: "; 
      cin >> center; 
      myCircle[thisPosition] = new Circle(radius, center); 
      myCircle[thisPosition]->PrintCircle(); 
      thisPosition++; 
      break; 

     case 2: // For printing a particular cirle from the list of cirles 
      cout << " Enter the Value for which Circle to Print: "; 
      cin >> printPosition; 
      myCircle[printPosition - 1]->PrintCircle(); 
      break; 

     case 3: // For printing all the circles in the class object array pointer list 
      cout << "\n"; 
      for (int i = 0; i < thisPosition; i++){ 
       myCircle[i]->PrintCircle(); 
       cout << "\n==============================" << endl; 
      } 
      break; 

     case 4: 
      cout << "\n Good Bye !!! \n " << endl; 
      break; 
     }  
     cout << "\nHere's the menu of choices: "; 
     cout << "\n1. Add a Circle.\n"; 
     cout << "2. Print a Circle. \n"; 
     cout << "3. Print all Cricles \n"; 
     cout << "4. Exit."; 
     cout << "Please enter your choice: "; 
     cin >> choice; 
     system("pause"); 
    } 
} 
+1

Ваш другой вариант - использовать кучу операторов стиля if, если в этом случае переключатель является лучшим выбором. – Annabelle

+1

Какой «другой вариант/альтернатив» вы имеете в виду? Утверждение 'switch', вероятно, лучше всего использовать в этом случае. – TypeIA

+4

Существует ряд опций, включая кучу операторов 'if' и' goto'. Скажите нам, почему * вы хотите избежать «переключения», было бы чрезвычайно полезно дать вам ответ, который действительно полезен. В чем проблема **, которую вы пытаетесь решить? Я подозреваю, что у вас есть проблема [XY] (http://meta.stackexchange.com/q/66377/167210). –

ответ

0

Использование если-иначе лестница является одной из альтернатив для отчетности коммутатора.

cout << " *********************Intensive Program 1***********************\n\n" << endl; 
cout << "\nHere's the menu of choices: "; 
cout << "\n1. Add a Circle.\n"; 
cout << "2. Print a Circle. \n"; 
cout << "3. Print all Cricles \n"; 
cout << "4. Exit.\n"; 
cout << "\nPlease enter your choice: "; 
cin >> choice; 
while (choice <4){ 

    if(choice==1) 
    { 
     // For adding cirles to the class 
     cout << " Enter the value for the radius of the circle: "; 
     cin >> radius; 
     cout << " Enter the value for the center of the circle: "; 
     cin >> center; 
     myCircle[thisPosition] = new Circle(radius, center); 
     myCircle[thisPosition]->PrintCircle(); 
     thisPosition++; 
    } 
    else if(choice==2) 
    { // For printing a particular cirle from the list of cirles 
     cout << " Enter the Value for which Circle to Print: "; 
     cin >> printPosition; 
     myCircle[printPosition - 1]->PrintCircle(); 
    } 
    else if(choice==3) // For printing all the circles in the class object array pointer list 
    { 
     cout << "\n"; 
     for (int i = 0; i < thisPosition; i++){ 
      myCircle[i]->PrintCircle(); 
      cout << "\n==============================" << endl; 
     } 
    } 
    else 
    { 
     cout << "\n Good Bye !!! \n " << endl; 
    } 
    }  
    system("pause"); 
} 
+0

Таблица указателей функций или аналогичных является лучшей заменой операторов switch с последовательными значениями. –

4

Вы можете также использовать std::vector<std::function<void()>> choices(5); ... и называть это как choices[choice](); после заполнения его с альтернативными выборами, как choices[1] = &function_1; и т.д ...

Но есть ощущение, реальный вопрос не действительно о том, как избежать switch ...

[EDIT]

Основываясь на ваш комментарий, я думаю, что вопрос заключается в том, чтобы избежать д вытесняя выход «меню». Просто рефакторинга, как это с помощью do..while:

cout << " *********************Intensive Program 1***********************\n\n" << endl; 
cout << "\nHere's the menu of choices: "; 
cout << "\n1. Add a Circle.\n"; 
cout << "2. Print a Circle. \n"; 
cout << "3. Print all Cricles \n"; 
cout << "4. Exit.\n"; 
cout << "\nPlease enter your choice: "; 
do 
{ 
    cin >> choice; 
    switch (choice){ 

     case 1: 
      // For adding cirles to the class 
      cout << " Enter the value for the radius of the circle: "; 
      cin >> radius; 
      cout << " Enter the value for the center of the circle: "; 
      cin >> center; 
      myCircle[thisPosition] = new Circle(radius, center); 
      myCircle[thisPosition]->PrintCircle(); 
      thisPosition++; 
      break; 

     case 2: // For printing a particular cirle from the list of cirles 
      cout << " Enter the Value for which Circle to Print: "; 
      cin >> printPosition; 
      myCircle[printPosition - 1]->PrintCircle(); 
      break; 

     case 3: // For printing all the circles in the class object array pointer list 
      cout << "\n"; 
      for (int i = 0; i < thisPosition; i++){ 
       myCircle[i]->PrintCircle(); 
       cout << "\n==============================" << endl; 
      } 
      break; 

     case 4: 
      cout << "\n Good Bye !!! \n " << endl; 
      break; 
     }  
     system("pause"); 
    } 
} while(choice != 4); 

Если вы все еще хотите, чтобы меню будет повторяться для каждого выбора, а затем просто вырезать и вставить печать меню в начале цикла do..while.

В качестве дополнительной заметки я настоятельно рекомендую вам в следующий раз прочитать https://mikeash.com/getting_answers.html.

Смежные вопросы