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 のままです。

EDITED:次はうまくいきます:

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 に答える