cscanf

How to fscanf `1/2` as `0.5` from a .dad file in C


I have a .dad file with the content

1/2

I wish to read from the file and save the value 0.5 into a double using fscanf, but the method reads it as 1.000.


To be completely clear, here is the code and the output:

#include <stdio.h>

int main(void){
    
    /* Open the file */
    FILE * file ;
    file = fopen ("test.dad", "r");
    if ( file == NULL ){
        printf("Error opening %s\n", ".dad file."); 
        return 1;
    }

    /* Import data to x */
    double x = 0;
    fscanf(file, "%lf", &x);      
    fclose(file); 

    /* Print x */
    printf("%lf\n", x);
    return 0;
}

Output:

1.000000

Solution

  • You get 1.0 because it only successfully parses 1 from 1/2. It has no clue what to do with /. What you need in this case is to read two integers separated by / and then divide those using double precision.

    Example:

    #include <stdio.h>
    
    int main(void) {
        char line[] = "1/2";
        int num, denom;
        if (sscanf(line, "%d/%d", &num, &denom) == 2) {
            double x = (double)num / (double)denom;
            printf("%lf\n", x);                        // prints 0.5
        }
    }