sscanf in C. Separating unknown number of doubles on a line to an array
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?开发者_C百科 It throws an error every time..
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.
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++ );
}
}
精彩评论