菜单驱动程序以无限循环结束

时间:2017-03-13 18:10:57

标签: c linux do-while

我一直在努力寻找一种方法来增强我在下面显示的简单菜单驱动的C代码中的错误检查。代码适用于正确的输入,但不幸的是,当给出不正确的参数时,它会进入无限循环。有人可以帮我处理这个案子吗?

这是我的代码:

#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;
}

代码在输入1,2,3,4 and any other integer下工作正常,但是当我输入字符或字符串时,代码进入无限循环。为什么?如何处理这种情况?

1 个答案:

答案 0 :(得分:3)

您可以检查scanf()功能的返回值。像这样:

if((scanf("%d", &choice)) != 1){
    printf("Invalid Argument\n");
    continue;
}
else
{
    //Your switch case logic
}