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。
EDITED: 下一步工作正常:
char *err;
double d = strtod(str.c_str(), &err);
if (strlen(err)) {
cout << "Please, enter number." << endl;
}
答案 0 :(得分:4)
什么样的“错误输入”?根据联机帮助页,errno
仅在输入数字太大或太小而无法存储在数据类型中时设置,但不时输入不是完全没有。
如果未执行转化,则返回零,
nptr
的值存储在endptr
引用的位置。如果正确的值会导致溢出,则返回正负HUGE_VAL,HUGE_VALF或HUGE_VALL(根据返回值的符号和类型),并且ERANGE存储在
errno
中。如果正确的值会导致下溢,则返回零,并将ERANGE存储在errno
。
答案 1 :(得分: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.