为什么当我向它传递一个数字后带有无效字符的字符串时,atof() 函数不是 return 0?

Why does the atof() function not return 0 when I pass it a string with invalid characters after a number?

我需要将字符串转换为浮点数。如果字符串不是数字,我希望 return 0.

我已尝试使用以下代码测试 atof() 函数是否适用于此:

printf("%f", atof("1a"));

根据我对atof的理解,当atof不能转换时,ed的值return是0,而这一行却打印出1.0.

为什么会这样?通过文档,我了解到只要输入不是数字,atof 就意味着 return 0。

我看到你查看了一些文档,但你一定错过了强调的部分——确保你彻底阅读文档很重要:http://www.cplusplus.com/reference/cstdlib/atof/

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

因此,该函数的行为完全正常 - "1a" 中的 a 字符被忽略。

来自 doc。强调我的

The function first discards as many whitespace characters (as in isspace) as necessary until the first non-whitespace character is found. Then, starting from this character, takes as many characters as possible that are valid following a syntax resembling that of floating point literals (see below), and interprets them as a numerical value. The rest of the string after the last valid character is ignored and has no effect on the behavior of this function.

yet this line prints 1.0.

printf("%f", atof("1a"));

之所以有效,是因为 atof 可以解析至少一个数字,即在这种情况下 1

但是:

char a[]="a1";
printf("%f\n",atof(a));

应该如您所料给您一个 return 值 0.0。