计算给定字符串的 float 的长度

标签 c string floating-point char converter

假设您有一个变量 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/

相关文章:

c - 将键盘输入存储到C中的整数数组中

javascript - 我们如何使用以正则表达式开头的字符串 (/^myString/g)

swift - stringVar.data.toString().replace ("", "") 相当于 swift

ScalaTest - 测试两个带误差范围的 float 组之间的相等性

c++ - 浮点 NaN 取决于 C++ 中不相关的异常处理

c - 汇编程序在调用 printf 后崩溃

c - 将字符数组传递给c中的函数

java - 在按钮上显示 float

c - 如何确定模糊的 c 类型

javascript - jQuery 用格式写入每个字符