#include <stdlib.h> double strtod(const char *str, char **end);
strtod
expects a floating-point number in C syntax, with these
specifications:
If the end
value is not NULL
, *end
is modified to address the
first character of the string that is not consistent with the
floating-point syntax above. However, if no initial segment of the
string can be interpreted as a floating-point number, str
is
assigned to *end
.
strtod
returns the double
value represented by the character
string up to the first unrecognized character. If no initial segment
of the string can be interpreted as a floating-point number, 0.0 is
returned.
errno
is set to ERANGE. In this case,
+- HUGE_VAL
(defined in <math.h>
) is returned if the
correct value is too large, or 0.0 if the correct value is too close to 0.
#include <stdlib.h> #include <ctype.h> #include <stdio.h> main() { double number; char *input, *stopchar; char string[20]; puts("Enter a string to be converted to double:"); input = gets(string); /* Skip space characters. */ while(isspace(*input)) ++input; /* Convert from character to double. */ number = strtod(input, &stopchar); /* Determine if string is valid. */ if (stopchar == input) printf("Invalid float number: %sn", input); /* Check for characters afterwards. */ else if (*stopchar && !isspace(*stopchar)) printf("Extra characters after value ignored: %sn", stopchar); printf("The entered string was converted to: %gn", number); }
strtol
Copyright (c) 1998 SAS Institute Inc. Cary, NC, USA. All rights reserved.