Originally Posted by
MK27
C has some standard library functions for converting a string to an integer -- strtol() -- or a float -- strtof(). Unfortunately, you cannot use those in order, because they convert the initial part of a string, so if the input was 123.5 and you try strtol() first, it will succeed and return 123. If the input was just 123 and you try strtof() first, it will return 123.0. Also, both functions will succeed for "23skidoo", which is a string, not a number.
They actually work fine if you examine the value returned in endptr. From the man pages
Originally Posted by
man strtol
SYNOPSIS
#include <stdlib.h>
long int strtol(const char *nptr, char **endptr, int base);
long long int strtoll(const char *nptr, char **endptr, int base);
...
If endptr is not NULL, strtol() stores the address of the first invalid character in *endptr. If there were no digits at all, strtol() stores the original value of nptr in *endptr (and returns
0). In particular, if *nptr is not '\0' but **endptr is '\0' on return, the entire string is valid.
...
RETURN VALUE
The strtol() function returns the result of the conversion, unless the value would underflow or overflow. If an underflow occurs, strtol() returns LONG_MIN. If an overflow occurs, strtol()
returns LONG_MAX. In both cases, errno is set to ERANGE. Precisely the same holds for strtoll() (with LLONG_MIN and LLONG_MAX instead of LONG_MIN and LONG_MAX).
Originally Posted by
man strtof
SYNOPSIS
#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
...
RETURN VALUE
These functions return the converted value, if any.
If endptr is not NULL, a pointer to the character after the last character used in the conversion is stored in the location referenced by endptr.
If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.
If the correct value would cause overflow, plus or minus HUGE_VAL (HUGE_VALF, HUGE_VALL) is returned (according to the sign of the value), and ERANGE is stored in errno. If the correct value
would cause underflow, zero is returned and ERANGE is stored in errno.
The way you handle this is by checking the contents of endptr. If it's a null character, you got to the end of the string:
Code:
char *endptr;
long long_value;
errno = 0; // clear errno
long_value = strtol(input, &endptr, 10); // try to convert input as base 10
if (errno == ERANGE || *endptr != '\0')=
// value was out of range, or there was extra characters at the end of input, not a valid integer
The code for strtof et al is very similar.