http://www.daniweb.com/code/snippet358.html
[edit]But the %n part would be to check whether all of the text entered was part of a valid floating point number. Like this:
Code:
#include <stdio.h>
#include <string.h>
int mygetd(double *result)
{
int n;
char buff [ 32 ];
if( fgets(buff, sizeof buff, stdin) != NULL)
{
char *newline = strchr(buff, '\n');
if (newline != NULL)
{
*newline = '\0';
}
}
return sscanf(buff, "%lf%n", result, &n) == 1 & (int)strlen(buff) == n;
}
int main(void)
{
double value;
do
{
fputs("Enter a floating-point number: ", stdout);
fflush(stdout);
} while ( !mygetd(&value) );
printf("value = %g\n", value);
return 0;
}
/* my output
Enter a floating-point number: one
Enter a floating-point number:
Enter a floating-point number: f12.3
Enter a floating-point number: -45.67
value = -45.67
Enter a floating-point number: -12.3f
Enter a floating-point number: 125 help
Enter a floating-point number: 1.2.3
Enter a floating-point number: 1.23
value = 1.23
*/