Question

g++ (Ubuntu/Linaro 4.6.1-9ubuntu3) 4.6.1

#include <errno.h>
...
cin >> str;
errno = 0 ;
double d = strtod(str.c_str(), NULL);
if (errno) {
    cout << "Please, enter number.";
}

on wrong input errno stay 0.

EDITED: Next works fine:

char *err;
double d = strtod(str.c_str(), &err);
if (strlen(err)) {
    cout << "Please, enter number." << endl;
}
Was it helpful?

Solution

What kind of “wrong input”? According to the manpage, errno is only set when the input is a number that is too large or too small to be stored in the data type, but not when the input isn’t a number at all.

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, or HUGE_VALL is returned (according to the sign and type of the return value), and ERANGE is stored in errno. If the correct value would cause underflow, zero is returned and ERANGE is stored in errno.

OTHER TIPS

It's all documented well:

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.

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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top