0

I have the following stored in a char array

"1, 1.0, 1.000, 1.0000"

I am trying to parse it into an int and three doubles with the following

sscanf(myString, "%d %lf %lf %lf", &(myStruct->I1), &(myStruct->D1), &(myStruct->D2), &(myStruct->D3);
printf("%d %lf %lf %lf", myStruct->I1, myStruct->D1, myStruct->D2, myStruct->D3);

outputs

1 0.000000 0.000000 0.000000
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

1 Answers1

1

The source string contains commas. So you need to change the format string in the call of sscanf.

Here you are.

#include <stdio.h>

int main( void ) 
{
    char myString[] = "1, 1.0, 1.000, 1.0000";
    struct myStruct
    {
        int I1;
        double D1;
        double D2; 
        double D3;
    } myStruct;
    
    sscanf( myString, "%d%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", 
            &myStruct.I1,&myStruct.D1, &myStruct.D2, &myStruct.D3 );
             
    printf( "%d, %.1f, %.2f, %.3f\n", 
            myStruct.I1, myStruct.D1, myStruct.D2, myStruct.D2 );
    
    return 0;
}

The program output is

1, 1.0, 1.00, 1.000

The format string can look even simpler like

"%d ,%lf ,%lf ,%lf"

Pay attention to that the length modifier l is redundant in the conversion specifier %lf when it is used in printf.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335