Link to home
Start Free TrialLog in
Avatar of DanJW
DanJW

asked on

Reading in from a file to a double array

Hi,

I need to be able to read from a file in the format eg.

0
-0.2334
0.48872
0.11330
-0.33340
-0.90202
-0.11133
0.89750
-0.10202
...

And I want it to be stored in a double array.  Any ideas how I can do this?
Avatar of sunnycoder
sunnycoder
Flag of India image

fscanf () is the shortest and most straight forward way

I, however, would recommend using fgets() to read in data as a string and then use a function like strtod to convert it into double. this provides you more flexibility and reliability. It is easy to perform input data validation using this technique.
This is the easy way out ..

FILE * fptr;
int i=0;
double arr[100];

fptr = fopen(...);
...
while (fscanf(fptr, "%lf\n", &arr[i]) != EOF )
     i++;
...
ASKER CERTIFIED SOLUTION
Avatar of brettmjohnson
brettmjohnson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of smpoojary
smpoojary

#include <stdio.h>
int main()
{
      FILE * fptr;
      int i;
      double arr[100];
      int nTotal;

      if((fptr = fopen("in.txt","r")) == NULL)
      {
            printf("ERROR: Unable to open input file\n");
            return 1;
      }

      i=0;
      while (fscanf(fptr, "%lf\n", &arr[i]) != EOF )
      {
            printf("%lf\n",arr[i]);
            i++;
      }
      nTotal = i;
      printf("Total number of lines = %d",nTotal);
      return 0;
}
use fscanf to store the number in formatted form