我需要将字符串转换为 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/