You can use strtod
. Check if the result is zero and subsequently if endptr == nptr
, according to the man page:
If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.
Something like this:
char input[50];
char * end;
double result = 0;
fgets(input, sizeof input, stdin);
errno = 0;
result = strtod(input, &end);
if(result == 0 && (errno != 0 || end == input)){
fprintf(stderr, "Error: input is not a valid double
");
exit(EXIT_FAILURE);
}
EDIT there seems to be a bit of a discrepancy between the standard and the man page. The man page says that endptr == nptr
when no conversion is performed, while the standard seems to imply this isn't necessarily the case. Worse still it says that in case of no conversion errno
may be set to EINVAL
. Edited the example code to check errno
as well.
Alternatively, sscanf
could be used (preferred over scanf
), in conjunction with fgets
:
/* just fgetsed input */
if(sscanf(input, "%lf", &result) != 1){
fprintf(stderr, "Error: input is not a valid double
");
exit(EXIT_FAILURE);
}
Also, don't forget to check the return value of fgets
for NULL
, in case it failed!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…