cwhile-loopsegmentation-faultdoublestrtod

C - extracting all Numbers from string


I got a String like by reading a file which got online one line. The C is a separator between the numbers.

3000C9.5452C5.644 ...

Now I want to extract all those numbers and write them into an double array whichs is called Matrix.

fgets(input_string, filesize, infile);
int matrix_size = (int) strtof(input_string, &input_end);
++input_string;
int binary_matrix_size = sizeof (double)*(matrix_size * matrix_size);
double *Matrix = malloc(binary_matrix_size);
for (int index = 0; index < (matrix_size * matrix_size); ++index) {
        while (!isdigit(input_string) && input_string) {
            ++input_string;
        }
        Matrix[index] = strtod(input_string, &input_end);
        input_string = input_end;
}

Solution

  • I tried to understand what you need.

    #include<stdio.h>
    #include <ctype.h>
    #include <stdlib.h>
    
    int main()
    {
        char *input_string = "2C9.5452C5.644";
        char *input_end;
    
        int matrix_size = strtol(input_string, &input_end, 10);
        printf("Array size: %d\n", matrix_size);
        input_string = input_end;
        double *Matrix = malloc(sizeof(double)*(matrix_size));
        for (int index = 0; index < matrix_size; ++index) {
                while ( (*input_string != '\0') && !isdigit(*input_string) && input_string ) {
                    ++input_string;
                }
                Matrix[index] = strtod(input_string, &input_end);
                printf("Retrieved value: %f\n", Matrix[index]);
                input_string = input_end;
        }
    
        free(Matrix);
    
        return 0;
    }
    

    Output is:

    Array size: 2
    Retrieved value: 9.545200
    Retrieved value: 5.644000