如何使用scanf阻止我的代码生成无限循环?

时间:2014-04-13 03:10:29

标签: c loops while-loop scanf

这是一个从main调用的函数。如何让代码检查字母输入,并在检测到非整数输入时进入while循环?感谢

int time1(void)
{
    int hour;

        printf("Enter the hour: ");
        scanf("%d", &hour);

            while (hour > MAX_HOUR || hour < MIN_HOUR) 
            {
                printf("Invalid hour input. Please enter an hour between 1 and 12: ");
                scanf("%d", &hour);
            }

            return hour;
}

2 个答案:

答案 0 :(得分:0)

你可以这样做:

int time1(void) {

    int hour;

    printf("Enter the hour: ");
    scanf("%d", &hour);

    if(hour>='0' && hour<='9')
    {
        while (hour > MAX_HOUR || hour < MIN_HOUR)
        {
            printf("Invalid hour input. Please enter an hour between 1 and 12: ");
            scanf("%d", &hour);
        }
    }

    return hour;
}

答案 1 :(得分:0)

测试它是成功还是失败:

hour = -1;   // So you can detect afterwards if they never succeeded at all

while ( 1 == scanf("%d", &hour) )
{
    if ( hour >= MIN_HOUR && hour <= MAX_HOUR )
         break;

    printf("Invalid hour input, try again...");
}

例如,如果他们输入"hello",该版本就会中断。如果你想在输入垃圾后继续询问它们,那么你必须清除流中的所有垃圾,例如:

for (;;)
{
    int result = scanf("%d", &hour);

    if ( result == EOF )
    {
        hour = -1;
        break;
    }

    if ( result != 1 )
    {
    // consume garbage which will end in a newline
        for (int ch; (ch = getchar()) != EOF && ch != '\n'; ) {}
        continue;
    }

    if ( hour >= MIN_HOUR && hour <= MAX_HOUR )
         break;

    printf("Invalid hour input, try again...");
}

在C中执行强大的流输入并不简单!