Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   Help to avoid using a Goto (http://www.go4expert.com/forums/help-avoid-using-goto-t2268/)

norbie 17Dec2006 01:45

Help to avoid using a Goto

I'm making a program here, and it's all functioning but I have had to use a Goto in order to achieve what I wanted. It's for my college homework and I may get marked down on it, so I'd like to avoid using it if possible.

Here is my code at the moment:


          cout << "\nPlease enter the altitude you will be flying at\n";
          cout<<"\nChoose 1 for    0 ft (Sea Level)\n";
          cout<<"Choose 2 for  5000 ft\n";
          cout<<"Choose 3 for 10000 ft\n";
          cout<<"Choose 4 for 15000 ft\n";
          cout<<"Choose 5 for 20000 ft\n";
          cout<<"Choose 6 for 25000 ft\n";
          cout<<"Choose 7 for 30000 ft\n";
          cout<<"Choose 8 for 35000 ft\n";
          cout<<"Choose 9 for 40000 ft\n";
                  case 1:(Alt=0);break;
                  case 2:(Alt=5000);break;
                  case 3:(Alt=10000);break;
                  case 4:(Alt=15000);break;
                  case 5:(Alt=20000);break;
                  case 6:(Alt=25000);break;
                  case 7:(Alt=30000);break;
                  case 8:(Alt=35000);break;
                  case 9:(Alt=40000);break;
                  default:cout<<"ERROR - Please choose a number from the list\n";

The idea is that if someone does not enter one of the numbers displayed for the switch/case statement, they will be taken back up the top again so they can retry it.

A goto works fine, but as I said I would like to get around this.
Any of you helpful people got a suggestion? Please post a code example if possible rather than just saying "do a loop" as I'm not too good on this lol.

Thankyou and Merry Xmas!

DaWei 17Dec2006 01:58

Re: Help to avoid using a Goto
Put it in a while loop. If they satisfy requirements, break from it. You can do this with a separate test in a while (true) loop, or possibly formulate the requirement in the while expression. Gotos are not evil, as many suggest, but there are very, very few conditions where one is a desirable solution. If you find that you need one, you are most likely weak on programming structure.

Aztec 17Dec2006 06:31

Re: Help to avoid using a Goto
It's actually the positioning of labels which is harmful in use of goto. Use them correctly then there should be no problems. But almost always there's another way to do it. Strive hard to make your code understandable by others.

All times are GMT +5.5. The time now is 03:51.