c - 如果字符串等于零,则返回 strtod() 的值

标签 c error-handling strtod

根据 MSDN:

  • 如果无法执行转换或发生下溢,strtod 将返回 0。

如果我的字符串等于零(即 0.0000)怎么办?我如何知道转换是否没有错误?

好的,我用下面的代码来验证一下想法:

char    *Y = "XYZ";
double  MyNum;
char    *MyEndPtr;
int     Err_Conversion = 0;

errno = 0;  //reset
MyNum = strtod (Y, &MyEndPtr);

if ( (MyNum == 0) && (errno != 0) && (strcmp(Y, MyEndPtr) == 0) )
        { Err_Conversion = 1;   }

我看到 MyNum = 0,但从未看到 Y 的内容复制到 MyEnPtr 中,或者在此强制错误中看到 errno = 0。有什么想法吗?

最佳答案

使用函数的str_end参数。例如:

const char* str = "123junk";
char* str_end;
double d = strtod(str, &str_end);
// Here:
//   d will be 123
//   str_end will point to (str + 3) (the 'j')

// You can tell the string has some junk data if *str_end != '\0'
if (*str_end != '\0') {
    printf("Found bad data '%s' at end of string\n", str_end);
}

如果转换完全失败,str 将等于 str_end:

const char* str = "junk";
char* str_end;
double d = strtod(str, &str_end);
// Here:
//   d will be 0 (conversion failed)
//   str_end will equal str

if (str == str_end) {
    printf("The string doesn't start with a number!\n");
}

您可以结合使用这两种方法来确保字符串(完全)成功转换(即通过检查 str != str_end && *str_end == '\0')

关于c - 如果字符串等于零,则返回 strtod() 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27973759/

相关文章:

c++ - std::strtod() 中的十进制错误与 Visual Studio 2015,64 位

c - 为什么带有 DBL_MIN 的 strtod() 给出 ERANGE?

c# - 母版页错误页中的ASP.NET自定义错误处理

r - 在命令行下运行R脚本时输出错误/警告日志(txt文件)

Apache 错误与 throws 类不兼容

c++ - strtod 不会在错误输入时设置 errno

c - 在 C 中使用 struct 的正确方法是什么?

python - Cython 将二进制文件读取为字符串并返回

c - 将文件描述符与 readlink() 一起使用

c++ - 使用Arduino编程ATtiny10( "ld.exe"错误)