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.