I have been struggling to figure out a way to enhance the error checking in my simple menu driven C code shown below. The code works fine with the right inputs, but unfortunately it goes in an infinite loop when an incorrect argument is given. Can somebody please help me handle this case?
Here is my code:
#include<stdio.h>
int main()
{
int choice, num, i;
unsigned long int fact;
system("clear");
do
{
printf("1.Factorial\n");
printf("2.Prime\n");
printf("3.Odd/Even\n");
printf("4.Exit\n");
printf("\nYour choice?");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\nEnter number:");
scanf("%d",&num);
fact = 1;
for(i=l;i<=num;i++)
fact=fact*i;
printf("\n Factorial value=%lu\n",fact);
break;
case 2:
printf("\n Enter number:");
scanf("%d",&num);
for(i=2;i<num;i++)
{
if(num%i== 0)
{
printf("\n Not a prime number.\n");
break;
}
}
if(i==num)
printf("\n Prime number.\n");
break;
case 3:
printf("\nEnter number:");
scanf("%d",&num);
if(num %2==0)
printf("\n Even number.\n");
else
printf("\nOdd number.\n");
break;
case 4:
break;
default:
printf("\nInvalid Argument.\n");
}
}while(choice != 4);
return 0;
}
The code works fine with the inputs 1,2,3,4 and any other integer
but when I enter a character or string, the code goes in an infinite loop. Why? How to handle this case?