程序在C中期望int时传递字符串

我有以下代码:

#include <stdio.h>

int main(){

    int a;

    while(1)
    {
        scanf("%d", &a);
        if(a >= 1000000 || a <= 9999)
        {
            printf("Error");
        }
        else
        {
            break;
        }
    }

return 0;
}

我希望用户键入类似20201的内容,如果输入无效,它将再次启动,但是我注意到当我键入2020.1时,程序返回:

ErrorErrorErrorErrorErrorErrorError...

并一直循环播放,不再询问该号码,为什么会这样?代码不是应该只打印一条错误消息并在scanf中再次等待输入吗?

评论
  • in_ut
    in_ut 回复

    Yes, it is supposed to. However, here, when the matching failure happens (due to the presence of . in the input), the input remains in the input buffer, and fed to next invocation of scanf(), only to fail again, thus going in infinite loop.

    发生故障后,您需要清除无效输入的输入缓冲区。