divide by zero
divide by zero

Reputation: 2370

scanf validate user input

I need to write a program in pure C. I wish to fill an array with user inputted floats and my function at the moment looks like this:

int fillWithCustom(float *array, int size) {
    float customNumber;
    for (i = 0; i < size; i++)
        for (j = 0; j < size; j++) {            
            printf("\n Enter [%d][%d] element: ", i , j);
            scanf("%f", &customNumber);
            *(array+i*size+j) = customNumber;
        }
    return 1;
}

But when I enter wrong number or char, iteration continues to an end...(Ex. I enter "a" as first element, then both for cycles iterate without scanf's and array is filled with 0's.

Upvotes: 0

Views: 1484

Answers (2)

pmg
pmg

Reputation: 108978

Don;t use scanf() for user input. It was written to be used with formatted data. User input and formatted data are as different as night from day.

Use fgets() and strtod().

Upvotes: 2

CrazyCasta
CrazyCasta

Reputation: 28302

Check the return value of scanf. From the man page of scanf:

RETURN VALUE
   These functions return the number of input items  successfully  matched
   and assigned, which can be fewer than provided for, or even zero in the
   event of an early matching failure.

   The value EOF is returned if the end of input is reached before  either
   the  first  successful conversion or a matching failure occurs.  EOF is
   also returned if a read error occurs, in which case the error indicator
   for  the  stream  (see ferror(3)) is set, and errno is set indicate the
   error.

To keep reading data until you get some, do:

while(scanf("%f", &customNumber) == 0);

If you want to fail if the user enters bad data, the do:

if(scanf("%f", &customNumber) == 0)
    break;

Upvotes: 1

Related Questions