【问题标题】:How to sscanf with negative float?如何使用负浮点数进行 sscanf?
【发布时间】:2021-11-08 15:33:35
【问题描述】:

其实我有一个这种类型的字符串:

"1,你好,E025FFDA,-126.56,52.34,true"

我想使用 sscanf 解析它,将这些值存储在相应类型的变量中

uint, char[], 可能是字符串, ufloat ?, float, bool

我将 sscanf 与 "%[^',']" 格式说明符一起使用,并在一定范围内测试每个值是否正确。

这是我的代码:

  • param 是指向字符串开头的指针
  • temp2 一个临时变量
  • local_ptr 是 param 的副本,不能修改 param
  • RCV 包含我所有参数的结构
if((get_param_length(param) != 0) && (sscanf(local_ptr, "%[^',']", &temp2) == 1))
    RCV.binarypayload = temp2;
else
    error = 1;

您知道存储我的值的最佳类型吗?或者有什么建议?

【问题讨论】:

  • 负浮点数就是float
  • 浮点数最好存储在 'float' 或 'double' 类型中
  • %[^','] 应该做什么?你的意思是%[^,]
  • 在我遇到的大多数情况下,无论如何都不需要使用浮点数,可以用定点算术代替(考虑可以使用子单位的货币,例如美分而不是欧元或美元,或者固定分数)。如果这对您来说是一个选项,您可以改为读取两个整数并计算最终结果。

标签: c string parsing scanf


【解决方案1】:

没有与您的ufloat 匹配的类型。所有浮点类型都经过签名,因此可以像这样从字符串中提取:

#include <math.h>     // if you want to use fabsf()
#include <stdbool.h>
#include <stdio.h>
#include <string.h>

int main() {
    unsigned u1, u2;
    char str1[20], boolstr[6];
    float f1, f2;
    const char *local_ptr = "1,Hello,E025FFDA,-126.56,52.34,true";
    bool b;

    if(sscanf(local_ptr, 
       " %u,%19[^,],%X,%f,%f,%5s", &u1, str1, &u2, &f1, &f2, boolstr) == 6)
    {
        b = strcmp(boolstr, "true") == 0;
        printf("%u %s %X %f %f %d\n", u1, str1, u2, f1, f2, b);
    }
}

可能的输出:

1 Hello E025FFDA -126.559998 52.340000 1

如果你想得到f1的绝对值,只需在sscanf后面加上f1 = fabsf(f1);即可。

【讨论】:

    【解决方案2】:

    假设"1,Hello,E025FFDA,-126.56,52.34,true"是你要解析的字符串,你可以这样做:

    #include <stdio.h>
    
    int main()
    {
        char string[] = "1,Hello,E025FFDA,-126.56,52.34,true";
    
        unsigned int i;
        char s1[10]; // You can adjust the size here and update it in sscanf()
        char s2[10];
        float f1, f2;
        char s3[10];
        
        if (sscanf(string, "%u,%9[^,],%9[^,],%f,%f,%9s", &i, s1, s2, &f1, &f2, s3) != 6)
            printf("Error parsing\n");
        else
            printf("%u, %s, %s, %f, %f, %s", i, s1, s2, f1, f2, s3);
    }
    

    这将输出:

    1, Hello, E025FFDA, -126.559998, 52.340000, true
    

    如果您想将"true" 存储在bool 中:

    bool b = !strcmp(s3, "true"); // else false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-05
      • 2021-07-07
      • 2011-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多