尝试清除输入缓冲区时无限循环

时间:2016-03-15 20:58:14

标签: c

在阅读完之前的问题之后,请确定:

Alternate method for clearing input buffer in c

How to clear input buffer in C?

我想出了一段代码来清空输入缓冲区并计算缓冲区中有多少个值,然后返回这个数字。然后进行比较以检查该数量是否超过允许的数量。

#include <stdio.h>
#include <stdlib.h>


int Empty();
int main()
{
    double x;
    int y=0;
    while(y==0)
    {
        y=1;

        if(scanf("%lf",&x)!=1 || Empty()>1) //checks if the value is acceppted
                                           // and then attempts to empty
                                           // the input buffer. I always expect 
                                          //at least 1 returned due to the 
                                          // EOF or '\n'
       {
            fprintf(stdout,"Invalid character(s) entered, please re-enter.\n");
            y=0;
       }
    }
    return(x);
}

int Empty()
{
    int clearr,n=0;
    do
    {
        n++;
    }while((clearr=fgetc(stdin))!= EOF && clearr !='\n'); // If EOF or '\n' is reached
                                                          // it ends, returning the 
                                                         //number of characters
    return(n);
}

如果我然后运行程序并输入2或2.2等,则接受并返回该号码。

如果我输入2a,或2 a或2 2等,它总是捕获空格/字母/等并强制使用SINGLE循环以允许您尝试重新输入值

但是,如果输入有问题的项目,即a,则首先发生无限循环。

这对我来说没有意义,因为根据我的理解,当fgetc(stdin)被调用时,它必须拉一个字符或EOF表示只输入一个项目,结束循环。

2 个答案:

答案 0 :(得分:1)

在测试if( A || B )中,如果A为真,则B 进行评估。

因此,如果scanf("%lf",&x)!=1为真,则不会调用Empty(),并且您的循环会一直持续。

这里的一个问题是你试图一次做几件事,建议是:

  • 保持简单
  • 无副作用

所以1)扫描输入,2)如果它可以继续,3)如果它没有冲洗并重复。

答案 1 :(得分:1)

如果输入a,scanf("%lf",&x)将给出0,因此它永远不会调用Empty。

相关问题