如何使用负浮点数进行 sscanf?

How to sscanf with negative float?

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

"1,Hello,E025FFDA,-126.56,52.34,true"

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

uint, char[], maybe string here, ufloat ?, float, bool

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

这是我的代码:

if((get_param_length(param) != 0) && (sscanf(local_ptr, "%[^',']", &temp2) == 1))
    RCV.binarypayload = temp2;
else
    error = 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);即可。

假设"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