• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 289
  • Last Modified:

reading float number from datafile

Hi,
  This should be rather easy but it is just driving me mad.
  I just want to read float numbers from a data file. My data file looks like this:

 -1.3635760e-002  8.9981614e-001
  3.7464906e-001  8.7696881e-002
  8.8600742e-001  2.4223525e-001
  5.4332379e-001  8.5243329e-001
  6.8148103e-001  6.7536886e-001
  8.3899312e-001  4.7851886e-001
  8.2437103e-001  9.4562145e-002
  2.5349397e-001  2.8462880e-001

Now I want to read all the numbers out and print them. My code looks like this:

FILE* inputFile;
double x,y;

inputFile=fopen("e:\\tmp\\test.dat","r");
if(inputFile == NULL) {
  printf("Error opening input data file. Exiting...\n");
  exit(1);
}
while(!feof(inputFile)) {
  fscanf(inputFile,"%e",&x);
  fscanf(inputFile,"%e",&y);
  printf("x=%f. y=%f.\n",x,y);
}
fclose(inputFile);

However, the outputs are like this:
x=-0.000000. y=-1.474790.
x=-0.000000. y=-1.474790.
x=-0.000000. y=-1.474790.
x=-0.000000. y=-1.474790.
x=-0.000000. y=-1.474790.
x=-0.000000. y=-1.474790.
...

Can anybody tell me where is my mistake? And what is the proper(hopefully best) way of doing this job? I am using MSVC5.0.

Thanks in advance.

sunjian
0
sunjian061197
Asked:
sunjian061197
  • 2
  • 2
1 Solution
 
newexpertCommented:
Try this:

while(!feof(inputFile)) {
  fscanf(inputFile,"%e %e ",&x, &y);
  printf("x=%f. y=%f.\n",x,y);
}

ie put spaces after and between %e.  This will tell fscanf to use white spaces (space, tab, newline character) as delimiters.

0
 
sunjian061197Author Commented:
Sorry newexpert, but I tried it and it didn't work!
0
 
chensuCommented:
"%e" expects float instead of double.

Replace

double x,y;

with

float x,y;

0
 
sunjian061197Author Commented:
Thank you chensu! You really solved my problem.

sunjian
0
 
chensuCommented:
When used with scanf, "%e" expects float. However, when used with printf, "%e" expects double. This is annoying.

And this is better.
  printf("x=%f. y=%f.\n",(double)x,(double)y);

0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now