Reading Scientific notation from file and storing in array

Hi,

I am trying to read a set of numbers that are in scientific notation into a file so I can do some math on them, but when I display the array contents the numbers aren't the same as the numbers in the file.

Could someone explain why? Thanks.

int main()
{

    double fArray[36];
    int i=0;
    FILE *fptr;

    fptr = fopen ("C:\\temp.txt", "r");

    if (fptr == NULL)

        printf ("Can't Find File to open\n");

    else
    {
        for (i=0; i <= 36; i++)
            {
            while (fscanf(fptr, "%lf", &fArray) != EOF);
            printf ("%e\n", &fArray);
            }
    }

return 0;
}

Text File Contents

1.973500e-08
1.972500e-08
1.971520e-08
1.975500e-08
1.960500e-08
1.972500e-08
1.736000e-07
1.735500e-07
1.736600e-07
1.735000e-07
1.735000e-07
1.735500e-07
1.291000e-06
1.288000e-06
1.291090e-06
1.290500e-06
1.289500e-06
1.290500e-06
9.856000e-06
9.823500e-06
9.845830e-06
9.837500e-06
9.837500e-06
9.837500e-06
8.102000e-05
8.068000e-05
8.086240e-05
8.094500e-05
8.086000e-05
8.086240e-05
6.591000e-04
6.597000e-04
6.611440e-04
6.634500e-04
6.616000e-04
6.611440e-04

Numbers read into array

6.951149e-308
6.951183e-308
6.951217e-308
6.951251e-308
6.951285e-308
6.951319e-308
6.951353e-308
6.951387e-308
6.951421e-308
6.951455e-308
6.951488e-308
6.951522e-308
6.951556e-308
6.951590e-308
6.951624e-308
6.951658e-308
6.951692e-308
6.951726e-308
6.951760e-308
6.951794e-308
6.951828e-308
6.951862e-308
6.951896e-308
6.951930e-308
6.951964e-308
6.951998e-308
6.952032e-308
6.952066e-308
6.952100e-308
6.952134e-308
6.952167e-308
6.952201e-308
6.952235e-308
6.952269e-308
6.952303e-308
6.952337e-308
6.952371e-308

Your printf is wrong:

printf ("%e\n", &fArray);

sscanf needs a pointer to the variable since it overwrites it. printf only expects the value itself. No & is necessary.

1 Like

Thanks for your help I got it.

Maybe it's this:

 while (fscanf(fptr, "%lf", &fArray) != EOF);

You have a semi colon after the while, so you're reading in every line from the file until EOF, then looping and doing it again (but it's already at EOF). You probably need to rethink how you're approaching this loop....

int main()
{

    double fArray[36];
    int i=0;
    FILE *fptr;

    fptr = fopen ("C:\\temp.txt", "r");

    if (fptr == NULL)

        printf ("Can't Find File to open\n");

    else
    {
        for (i=0; i <= 36; i++)
            {
            if (fscanf(fptr, "%lf", &fArray) == EOF) break;  /* stop if we ran out of values */
            printf ("%le\n", fArray);  /* use le since you're printing a double not a float */
            }
    }

return 0;
}
1 Like