Read the file as both floating and double?

How can I fscanf for float and double, since I have declared global precision once in single precision (float) and once in double precision (double) ... so when I run it I have to change it every time I convert to another type

in double (% lf) in single (% f)

fscanf(fp1,"%lf", &a[i][j]);

      

so is there a way that works for both and doesn't need to change it every time?

+3


source to share


1 answer


It's been a while since I've done any coding in C, so you might want to confirm with experimentation, but all single precision floats are valid double precision floats, so you can just use "% lf" in fscanf , store to temporarily float in double precision and then use logic to assign the correct variable.

Alternatively, if you are using "#define", you can simply do something like:



#define USE_DOUBLE
#ifdef USE_DOUBLE
#define STORTYPE double
#define SCANSTRING "%lf"
#else
#define STORTYPE float
#define SCANSTRING "%f"
#endif
...
STORTYPE a[x][y];
fscanf(fp1,SCANSTRING, &a[i][j]);

      

+3


source







All Articles