Search code examples
cfileiofloating-pointfile-handling

I want to fetch double values from a file in C language


I have a numbers.txt file which have some data in this format number0 :23.95 number1 :90.25 number2 :77.31 number3 :27.84 number4 :90.03 number5 :19.83 like this and I want sum of all the floating point number (23.95 + 90.25 + 77.31 + 27.84 + 90.03 in this case) in C programming language. I just can't figure out how to fetch these floating point number, if the numbers.txt would have been 34.22 44.56 89.44 then it would be easy but I can't change file format here. Can anyone help with the same? Providing screenshot of numbers.txtenter image description here


Solution

  • You can use fscanf for this job:

    #include <stdio.h>
    
    int main() {
        FILE *fp = fopen("numbers.txt", "r");
        if (fp == NULL) {
            fprintf(stderr, "Cannot open %s\n", "numbers.txt");
            return 1;
        }
        int count = 0;
        double d, sum = 0.0;
        while ((fscanf(fp, " number%*[0-9] :%lf", &d) == 1) {
            sum += d;
            count++;
        }
        fclose(fp);
        printf("read %d numbers, sum: %g\n", count, sum);
        return 0;
    }
    

    The above code will match the file contents more strictly than fscanf(fp, "%*s :%lf", &d): the scan keep iterating as long as the file contents match this: optional white space followed by the characters number immediately followed by a number, then optional white space, a colon, more optional white space and a floating point number.