0

I am trying to use fscanf to read matrix data in a text file and do some matrix*vector calculation in C. However I noticed that fscanf read very small number such as -2.22E-10 to zero. Here is the code for reading the matrix from "D1_1.txt" file.

file = fopen("D1_1.txt", "r");
    for (j = 0; j < matcols; j++) {
        for (i = 0; i < matrows; i++) {
            if (!fscanf(file, "%lf", &(data->D1_1data)[j + i*matcols]));  
        }
    }
fclose(file);

And here is the screenshot image of the original data

enter image description here

And below, screenshot of the data read by fscanf (I use fprintf to write another txt file from C code)

enter image description here

As you can see, large number can be correctly read by fscanf but not very small number such as 5.92e-10.

Is %lf not a good choice here ? What should I use to read all the numbers correctly ?

Thanks,

Derik
  • 57
  • 2
  • 7
  • 1
    What was the format used in fprintf? – stark Jan 13 '21 at 21:03
  • Thanks for your comment. Same as %lf – Derik Jan 13 '21 at 21:17
  • 1
    *I use fprintf* - it is likely the problem, and not `fscanf`. – Eugene Sh. Jan 13 '21 at 21:18
  • So you only get 6 digits. – stark Jan 13 '21 at 21:19
  • Check this: https://stackoverflow.com/questions/21287974/why-is-printf-not-using-scientific-notation – Eugene Sh. Jan 13 '21 at 21:19
  • Thanks. Eugene. what should I use for fprintf instead of %lf ? – Derik Jan 13 '21 at 21:24
  • 1
    Check the linked answer. It explains how to make it print in scientific notation. – Eugene Sh. Jan 13 '21 at 21:25
  • Thank you all. I just confirmed that `fscanf` is not an issue. `fprintf` should use with scientific notation like %.10e to print the small number correctly. – Derik Jan 13 '21 at 21:37
  • 1
    _Side note:_ Based on your data image, `matcols` is 4 and `matrows` is 8. Normally, you want row elements to be physically contiguous. But, AFAICT, you're reading the matrix in transposed. You may want to flip the order of your `for` loops. Also, I know it's taught in school to use `i` and `j`, but [IMO, based on experience], it's better to use something more descriptive (e.g.) `irow` and `icol` – Craig Estey Jan 13 '21 at 22:25

0 Answers0