Home > Software design >  How to sscanf with negative float?
How to sscanf with negative float?

Time:09-16

Actually I have a string with this type:

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

And I want to parse it using sscanf to store those value in variable of corresponding type so

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

I use sscanf with "%[^',']" format specifier and I test each value if it is correct or not and in a certain range.

Here is my code:

  • param is the pointer to the beginning of the string
  • temp2 a temporary variable
  • local_ptr is a copy of param to not modify param
  • RCV a struct with all my parameters
if((get_param_length(param) != 0) && (sscanf(local_ptr, "%[^',']", &temp2) == 1))
    RCV.binarypayload = temp2;
else
    error = 1;

Do you have any idea of the best type to store my values? Or maybe any advice?

CodePudding user response:

There is no type that could match your ufloat. All floating point types are signed so extracting from your string could be done like this:

#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,[^,],%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);
    }
}

Possible output:

1 Hello E025FFDA -126.559998 52.340000 1

If you want to get the absolute value from f1, just add f1 = fabsf(f1); after the sscanf.

CodePudding user response:

Assuming "1,Hello,E025FFDA,-126.56,52.34,true" is the string you want to parse, you can do it like this:

#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);
}

This will output:

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

If you want to store "true" in a bool:

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