fscanf problems

I haven't needed to use fscanf before, so I'm not very familiar with it... Everything is working fine except that the numbers it inputs are not what's in the file and they are all the same number (-9.255959e+061 to be specific) I know exactly how the files are formatted they are opening and everything... so I'm not sure what's wrong.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <math.h>
#include <stdio.h>
#include <iostream>

int main ()
{
  char fname [80];
  const int num=16;
  double ke[50],tbin[50],ket1[50],ket2[50],tbin1[50],tbin2[50],k,t;
  int i,j,extra;
  FILE * fin;
  FILE * fout1;
  FILE * fout2;
  for(i=0;i<50;i++){ket1[i]=0.;ket2[i]=0;tbin1[i]=0;tbin2[i]=0;ke[i]=0;tbin[i]=0;}
  fout1=fopen("avgke1.txt","w");
  fout2=fopen("aveke2.txt","w");
  for (i=0;i<num;i++){
  sprintf(fname,"avgkei_100_1.5e-07_1_1.00_%i.txt",i);
  fin = fopen (fname,"r");
  printf("file open");
  if (fin!=NULL){
  for (j=0;j<49;j++){
	  fscanf(fin,"%e %e %i",&t,&k,&extra);
	  ke[j]=k;
	  tbin[j]=t;
  printf("%e %e\n",tbin[j],ke[j]);
  //getchar();
  if(i<(num/2)){
	  ket1[j]+=ke[j];
	  tbin1[j]+=tbin[j];
  }
  else{
	  ket2[j]+=ke[j];
	  tbin2[j]+=tbin[j];
  }
  }
 
  fclose (fin);
  }
  } 
  for(i=0;i<50;i++){
	  ket1[i]=ket1[i]/(num/2);
	  tbin1[i]=tbin1[i]/(num/2);
	  ket2[i]=ket2[i]/(num/2);
	  tbin2[i]=tbin2[i]/(num/2);
	  fprintf(fout1,"%13.6e %13.6e\n",tbin1[i],ket1[i]);
	  fprintf(fout2,"%13.6e %13.6e\n",tbin2[i],ket2[i]);
  }

  fclose(fout1);
  fclose(fout2);
}
Your conversion specifier is for float, but your variables are type double. Fix it thus:

23
24
	  fscanf(fin,"%le %le %i",&t,&k,&extra);
	  ...


[edit] The format specifiers are correct for the [f]printf() functions... since the arguments are passed as double even if you use float. [/edit]

If I may ask though, since you are using C++, why not just use C++ iostreams? It would make your life a lot simpler.
Last edited on
He's not actually. I don't see anything C++ in that code except for the iostream up there. But this confusion is inevitable since C++ is almost a superset of C.
but if #include <iostream> compiles, then he's compiling as C++, which means he can use streams =P
good point.
Topic archived. No new replies allowed.