在 Visual Studio 2013 中,我有以下测试代码:
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ( int argc, const char* argv[])
{
static const char* floatStr = "3.40282346638528859811704183485E+39";
static const char* doubleStr = "1.79769313486231570814527423732E+309";
char* end;
float floatVal = 42.0f;
double doubleVal = 42.0;
errno = 0;
floatVal = strtof(floatStr, &end);
printf("Conversion of '%s':\nfloatVal=%f\nerrno='%s'\n",
floatStr,
floatVal,
strerror(errno));
errno = 0;
doubleVal = strtod(doubleStr, &end);
printf("Conversion of '%s':\ndoubleVal=%f\nerrno='%s'\n",
doubleStr,
doubleVal,
strerror(errno));
return 0;
}
目的是显示在非常大(溢出)输入上使用 strtof() 和 strtod() 函数时观察到的行为。
我发现 strtof() 函数会将浮点值设置为 +INF 但不会设置 ERANGE errno。然而,strtod() 函数将 double 值设置为 +INF 并设置 ERANGE 错误号:
Conversion of '3.40282346638528859811704183485E+39':
floatVal=1.#INF00
errno='No error'
Conversion of '1.79769313486231570814527423732E+309':
doubleVal=1.#INF00
errno='Result too large'
这种行为是预期的,还是特定于实现的细微差别?
旁注:在我看来 strtof() 可能正在调用 strtod() 并且在从 double 到 float 的转换产生 +INF 结果后没有正确设置 errno ?
最佳答案
正如 WeatherVane 所指出的,这在 VS2015 中不会发生,并且似乎是 VS2013 实现中的一个错误。
关于c - VS2013 : strtof doesn't set ERANGE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539382/