问题描述:

How would I be able to clear the buffer if a character or more is entered in this block of code.

int x = 1;

float grade = 0.0;

do

{

printf ("Enter a grade for quiz %d: ", x);

scanf ("%f", grade);

if (grade >= 1 && grade <= 10) break;

printf ("Entry not valid. Please try again\n");

} while (1);

My instructor is insisting that we use fflush(stdin). This I know wont work, and I called him out on it. What other ways could I just to validate if a number is entered or not.

网友答案:
void flush_stdin ()
{
    char c;
    do
    {
        c = get(stdin);
    }while(c != EOF && c != '\n');
}

I use this in my own code, basically, read every character in stdin until you encounter a sign that it is now empty.

I ll also urge to avoid scanf, but prefer using fread with sscanf, so you can limit the number of input character, wich avoid buffer overflow and other nasty things.

网友答案:

Rather than attempting to flush the input buffer on a bad read, always read a whole line using fgets()/sscanf().

Example Read_long

do
{
    char buf[50];
    printf ("Enter a grade for quiz %d: ", x);
    if (fgets(buf, sizeof buf, stdin) == NULL) 
        Handle_EOForIOError();
    if (sscanf(buf, "%f", grade) == 1 && grade >= 1 && grade <= 10) 
        break;
    printf ("Entry not valid. Please try again\n");
} while (1);
相关阅读:
Top