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

标签 c ansi-c atof

我需要将字符串转换为 float 。如果字符串不是数字,我希望返回 0。

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

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

根据我对atof的理解,atof无法转换时返回的值为0,而这一行却打印出1.0

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

最佳答案

来自 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.

关于c - 为什么当我向 atof() 函数传递一个数字后带有无效字符的字符串时,atof() 函数不返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37330513/

相关文章:

c - 注释掉未使用的行后,Switch-case 不会编译

c - C中空结构的大小是多少?

c - 从 cstring 中删除空字符

c - Atof 不能在 C 中工作,没有 atof 也不能在调试中工作

c++ - 带有gcc 7.4.0的奇怪std::atof错误

c - 基础 C 快速排序

c - 2 个 printf() 之间的程序段错误

c - 错误: expected expression before ‘char’

c - 信号处理不适用于 -ansi 或 POSIX define

c++ - 对整数使用 atof