Home > Software engineering >  I want to fetch double values from a file in C language
I want to fetch double values from a file in C language

Time:04-06

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

CodePudding user response:

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 will stop if the file does not contain number immediately followed by a number, then optional white space, a colon, more optional white space and a floating point number.

CodePudding user response:

  1. Check the line for a ":" character, possibly using strchr.

  2. If there is a colon, parse starting one character after it, possibly using atof.

  • Related