I am having a problem with a menu system, it's a sample menu system that I am putting together to make sure it will work, theoretical reasons, just trying to learn.
When an invalid value is entered it will go into an infinite loop and the program has to be forcefully terminated.
Can someone explain to me how to prevent this.
Code:
/* using an infinite loop and switch statement
to implement a menu system */
#include <stdio.h>
#include <stdlib.h>
#define DELAY 150000
int menu(void);
void delay(void);
int main()
{
while (1)
{
/* get user's selection and branch based on the input */
switch(menu())
{
case 1:
{
puts("\nExecuting choice 1");
delay();
break;
}
case 2:
{
puts("\nExecuting choice 2");
delay();
break;
}
case 3:
{
puts("\nExecuting choice 3");
delay();
break;
}
case 4:
{
puts("\nExecuting choice 4");
delay();
break;
}
case 5: /* exit program */
{
puts("\nExiting program now...\n");
delay();
exit(0);
}
default:
{
puts("\nInvalid choice, try again");
delay();
}
}/* end of switch */
} /* end of while */
}
/* displays a menu and inputs user selection */
int menu(void)
{
int reply;
puts("\nEnter 1 for task A");
puts("Enter 2 for task B");
puts("Enter 3 for task C");
puts("Enter 4 for task D");
puts("Enter 5 to exit program");
scanf("%d", &reply);
return reply;
}
void delay(void)
{
long x;
for (x = 0; x < DELAY; x++)
;
}
Thanks in advance.