-1

I'm writing a program to calculate net pay. The user will enter a number that will correspond to a menu choice (5 choices). I've got most of it working, except that it should re-prompt the user if they don't enter an integer 1-5, and it should repeat the program until the user chooses the quit option. I tried some goto stuff and it mostly worked, but I've been told to stay away from goto.

How can I get the program to go back to the beginning if the user enters something other than the integers 1-5, and to repeat until 5 is entered?

Here's some of the code: I deleted some of the #define statements that say what WAGE1 WAGE2 etc. are. Also, the function definition of pay() is not here, it works fine.

#include <stdio.h>
void pay(float wage);
int main(void)
 {
   int choice;
   start :
   printf("--------------------------------------------------------------------\n");
   printf("Enter the number corresponding to the desired pay rate or action:\n");
   printf("1) $8.75/hour                     2) $9.33/hour\n");
   printf("3) $10.00/hour                    4) $11.20/hour\n");
   printf("5) quit\n");
   printf("--------------------------------------------------------------------\n");

   scanf("%d", &choice);

   switch(choice)
   {
   case 1 : pay(WAGE1); break;
   case 2 : pay(WAGE2); break;
   case 3 : pay(WAGE3); break;
   case 4 : pay(WAGE4); break;
   case 5 : printf("Goodbye!\n"); break;
   default : printf("Please enter 1, 2, 3, 4, or 5.\n");    
   }

   system("PAUSE"); 
   return 0;
 }

Also, if this isn't a good question, could you tell me why? Then I can ask a better one next time.

Zak.
  • 41
  • 2
  • 7
  • 1
    what exactly is your question? – Daniel A. White Oct 13 '14 at 23:35
  • change your line to: `default : printf("Please enter 1, 2, 3, 4, or 5.\n"); goto start;` and it should work. But using `goto` is bad. – Icemanind Oct 13 '14 at 23:36
  • How can I get it to ask again if the user enters something besides 1-5. I edited it to make it more clear. I tried changing it to that, but it goes to an infinite loop if it gets something besides 1-5. – Zak. Oct 13 '14 at 23:38
  • 1
    You use a [while](http://en.wikipedia.org/wiki/While_loop) loop. Another type of loop available to you is a [for](http://en.wikipedia.org/wiki/For_loop) loop. – indiv Oct 13 '14 at 23:40
  • Not related to your problem, but you shouldn't use a switch statement for this but you should put the wages into an array and index thet array with your choice. – Jabberwocky Oct 14 '14 at 09:41

1 Answers1

0

Remove the default case and change your scanf to

   do {
     scanf("%d", &choice);
     if (choice < 1 || choice > 5)
       printf("invalid input.Try again \n");
   } while(choice < 1 || choice > 5);
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Spikatrix
  • 20,225
  • 7
  • 37
  • 83