Reading data from text file in VC++ 2010

Apr 14, 2016 at 8:09pm
FILE *gdata;
gdata=fopen("a1.txt","r");
for( n=1;n<=50;n++)

fscanf(gdata,"%f %f %f\n",&x1[n],&y1[n],&z1[n]);
fclose(gdata);
for( n=1;n<=50;n++)
//printf("%f %f %f\n",x1[n],y1[n],z1[n]);
unable to get anything except 0 0 0 entries
where a1.txt file containing numerical data points
Apr 14, 2016 at 9:05pm
That code seems to work for me.
Did the file open successfully?
If so, does it contain numeric data?

check return value from fopen()
http://www.cplusplus.com/reference/cstdio/fopen/

check number of items read by fscanf()
http://www.cplusplus.com/reference/cstdio/fscanf/
Apr 15, 2016 at 8:27am
Here is a simple sample:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <stdlib.h>

const int NUM_ITEMS = 6;

int main ()
{
  FILE *gdata;
  float x1[NUM_ITEMS], y1[NUM_ITEMS], z1[NUM_ITEMS];

  gdata = fopen ("a1.txt", "rt");
  if (gdata == NULL)
  {
    fprintf (stderr, "Error opening file a1.txt");
    system ("pause");
    return EXIT_FAILURE;
  }
  for (int n = 0; n < NUM_ITEMS; n++)
    fscanf (gdata, "%f %f %f\n", &x1[n], &y1[n], &z1[n]);
  fclose (gdata);

  for (int n = 0; n < NUM_ITEMS; n++)
    printf("%.2f %.2f %.2f\n",x1[n],y1[n],z1[n]);

  system ("pause");
  return 0;
}


a1.txt
1
2
3
4
5
6
1.1 2.2 3.3 
4.4 5.5 6.6
1.1 2.2 3.3 
4.4 5.5 6.6
1.1 2.2 3.3 
4.4 5.5 6.6


Output
1.10 2.20 3.30
4.40 5.50 6.60
1.10 2.20 3.30
4.40 5.50 6.60
1.10 2.20 3.30
4.40 5.50 6.60
Press any key to continue . . .
Topic archived. No new replies allowed.