The problem with converting a string to a number (strtod)

I use the strtod () function to extract the environment variable as a string, and then change it to double with strtod:

enter code here
 char strEnv[32];
 strncpy(strEnv, getenv("LT_LEAK_START"), 31);
 // How to make sure before parsing that env LT_LEAK_START is indeed a number?
 double d = strtod(strEnv, NULL);

Now I want to make sure that this number entered by the user is a number, not a string or a special character. How can I be sure of this?

The code snippet will be very useful.

Thanks in advance.

+5
source share
6 answers

The second argument to the function is useful strtod.

char *err;
d = strtod(userinput, &err);
if (*err == 0) { /* very probably ok */ }
if (!isspace((unsigned char)*err)) { /* error */ }

Edit: added examples

strtod 1- double , char, .

input         result
----------    ----------------------------
"42foo"       will return 42
              and leave err pointing to the "foo" (*err == 'f')

"     4.5"    will return 4.5
              and leave err pointing to the empty string (*err == 0)

"42         " will return 42
              and leave `err` pointing to the spaces (*err == ' ')
+12

man strtod: , nptr , endptr.

char * endptr;
double d = strtod(strEnv, &endptr);
if (strEnv == endptr)
   /* invalid number */
else
   ...
+2

, , man strtod() . . Linux- :

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.

, , . , , , getenv(); , .. .

+2
  • getenv - NULL, .
  • -, getenv NULL, .
  • -, char ** endptr strtod NULL, , 0.0.
+1

strtod, NULL, char; -to-char, , , strtod . , , , , , , . .

0

, , strtod() 0.0, . , - .

0

All Articles