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。
编辑: Next工作正常:
char *err;
double d = strtod(str.c_str(), &err);
if (strlen(err)) {
cout << "Please, enter number." << endl;
}发布于 2012-03-21 19:05:10
什么样的“错误输入”?根据手册页,只有当输入的数字太大或太小而无法存储在数据类型中时,才会设置errno,但当输入根本不是数字时就不会设置。
如果不执行任何转换,则返回零,并将
nptr的值存储在endptr引用的位置。
如果正确的值会导致溢出,则返回正负HUGE_VAL、HUGE_VALF或HUGE_VALL (根据返回值的符号和类型),并将ERANGE存储在errno中。如果正确的值会导致下溢,则返回零,并将ERANGE存储在errno中。
发布于 2012-03-21 19:06:33
所有这些都有很好的文档记录:
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.https://stackoverflow.com/questions/9803196
复制相似问题