0

OK so after reading these previous questions:

Alternate method for clearing input buffer in c

How to clear input buffer in C?

I came up with a piece of code to empty the input buffer and count how many values were in the buffer, then return this number. A comparison is then made to check if the number exceeded the allowed number.

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

If i then run the program and enter 2 or 2.2 etc, the number is accepted and returned.

If i enter 2a, or 2 a or 2 2 etc it always catches the space/letter/etc and forces a SINGLE loop to allow you to try and reenter a value

If, however if enter the offending item, i.e the a, first then an infinite loop occurs.

This does not make sense to me as from what i understand, when the fgetc(stdin) is called it MUST pull either a character or an EOF which would signify only one item has been entered, ending the loop.

Community
  • 1
  • 1

2 Answers2

1

In a test if( A || B ), if A is true, B is not evaluated.

So if scanf("%lf",&x)!=1 is true, Empty() is not called and your loop continues forever.

One of the problems here is that you try to do several things at once, the advice would be:

  • keep things simple
  • no side effects

So 1) scan the input, 2) if it's ok move on, 3) if it's not flush and repeat.

Ilya
  • 5,377
  • 2
  • 18
  • 33
1

If you enter a , scanf("%lf",&x) will give 0 and hence it never calls Empty.

Priyansh Goel
  • 2,660
  • 1
  • 13
  • 37