根据 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/