假设您有一个变量 char s[30]
,并且 s
以正 float 开头,例如
s = "15.016这不是 float 的一部分!";
float 后面的字符不能是数字。
目标是确定表示 float 的字符数,例如|15.016| = 6.
我正在尝试编写一个简单的代码来执行此操作,最好不要使用任何外部库。
我有:
int count_len(char *s)
{
char tmp_buf[30];
int integral_digits = sprintf(tmp_buf, "%d", atoi(s) );
return integral_digits + sprintf(tmp_buf, "%d", atoi(s + integral_digits +1) );
}
这适用于任何分数不包含前导零的数字(适用于 15.16,但不适用于 15.016)。
你会如何修复这个函数?
最佳答案
为什么不简单地使用带有特殊格式说明符的 sscanf
?
考虑
sscanf("15.01336This is not a part of the float !", "%*f%n", &len);
%*f%n
表示
%*f
读取一个 float 但不将其存储在任何地方,只使用它。%n
存储到目前为止消耗的字符数。
一个工作示例
#include <stdio.h>
int main()
{
int len;
sscanf("15.01336This is not a part of the float !", "%*f%n", &len);
printf("%d\n", len);
return 0;
}
关于计算给定字符串的 float 的长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31473589/