2

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.";
}

输入错误时errno保持 0。

编辑:下一步工作正常:

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

2 回答 2

4

什么样的“输入错误”?根据手册页,errno仅当输入的数字太大或太小而无法存储在数据类型中时才设置,而不是当输入根本不是数字时。

如果不执行转换,则返回零并将 的值nptr存储在 引用的位置endptr

如果正确的值会导致溢出,则返回加减 HUGE_VAL、HUGE_VALF 或 HUGE_VALL(根据返回值的符号和类型),并将 ERANGE 存储在errno. 如果正确的值会导致下溢,则返回零并将 ERANGE 存储在errno.

于 2012-03-21T11:05:10.433 回答
1

这一切都有很好的记录:

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.
于 2012-03-21T11:06:33.080 回答