I am using strtod( ) function to extract an environment variable as a string, and then changing it to double using 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 user is a number and not a string or special character. How can i make sure of that?
A code snippet would be of great help.
Thanks in advance.
That second argument to
strtod
, which you've set toNULL
, can be a pointer-to-pointer-to-char; the pointer-to-char that it points to will get set to the character after the last thingstrtod
managed to parse. If that's the end of the string, or at least there's nothing after it but whitespace, then what you had was a number. Otherwise, it was something else.Surely you could do worse than just reading the man page for strtod() and acting upon that. E.g. on my Linux system it says:
That pretty much tells you what you need to do in order to handle errors. Also, like Johann Gerell said, you also need to check whether getenv() succeeded; a similar approach works there, i.e. check the man page and write error handling code according to that.
The 2nd argument to the
strtod
function is useful.Edit: examples added
The
strtod
function tries to convert the initial portion of the 1st argument to a double and stops either when there are no more chars, or there is a char that can't be used to make a double.man strtod
: If no conversion is performed, zero is returned and the value of nptr is stored in the location referenced by endptr.I don't know much about this language but I do know that strtod() will return 0.0 if the input is wrong. Maybe you could use a regular expression to validate the input string is a number.
getenv
- if it's NULL, then that environment variable doesn't exist.getenv
isn't NULL, then you have the value, as a string.char ** endptr
parameter ofstrtod
to NULL, but use it to check the validity of the converted value, also check for0.0
.