sscanf in C. Separating unknown number of doubles

2019-08-08 20:26发布

问题:

I there are similar questions out there, but none of that did really help me with my problem. I get a string with unknown number of floating point numbers and I have to cut them seperatly to an array.

What I've got is:

   h=0;
   while(fstring[h]!='\n'){  //So first I count how many spaces there are in the string
            if(fstring[h]==' '){
                sc++;
            }
            h++;
    }
    vars=sc;
    for(h=0;h<vars;h++){
        sscanf(fstring,"%lf",&scanned);
        matrix[h]=scanned;
    }

So why does this not work? It throws an error every time..

回答1:

You could do something like this instead:

#include <stdio.h>

int main ()
{
    double fmatrix[100] = { 0 };
    double *matrix = fmatrix;
    double scanned;
    int bytesread;
    char string[100];
    char *fstring = string;
    int i;

    fgets ( string, 99, stdin );
    fstring = string;

    while ( sscanf ( fstring, "%lf%n", &scanned, &bytesread ) > 0 )
    {
        fstring += bytesread;
        *matrix++ = scanned;
    }

    matrix = fmatrix;

    for ( i = 0; i < 50; i++ )
    {
        printf ( "%lf\n", *matrix++ );
    }
}


回答2:

I strongly recommend the use of strtod rather than sscanf here. Something like this should work:

char *ptr, *endptr = fstring;
int h = 0;
do {
    ptr = endptr;
    matrix[h++] = strtod(ptr, &endptr);
} while (endptr != ptr && isspace(*endptr) && *endptr != '\n');

Memory allocation and recovery from ill-formed input left as an exercise.