Rather than using scanf, you can have greater control over error checking by using fgets to read an entire line and then parsing it with strtod. Here is an example of a validation function for floating-point values:
Code:
#include <stdlib.h>
#include <string.h>
#include <errno.h>
/*
* Validate a string for floating-point input, save
* the value in 'result'.
*
* Returns:
* 0 - Failure, 'result' is either HUGE_VAL or 0
* 1 - Successful validation, 'result' contains a valid double
* 2 - Extraneous characters, 'resut' contains a valid double
*/
int validate_float ( char *line, double *result )
{
char *endp;
size_t len = strlen ( line );
errno = 0;
*result = strtod ( line, &endp );
if ( errno == ERANGE || endp == line )
return 0; /* Real error */
if ( endp != line + len && *endp != '\n' )
return 2; /* Extraneous characters */
return 1;
}
It isn't bulletproof, but good enough for most uses.