read a file from both float and double?

Go To StackoverFlow.com

3

How can I fscanf for both float and double, as I declared a global precision once in single precision (float) and once in double precision (double)... so when I run it, I have to change it everytime that I convert to a different type

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

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

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

2012-04-04 01:01
by soso101
You mean you want printf() to automatically select between float and double depending on the type of the parameter you passed it - Mysticial 2012-04-04 01:03
@Mysticial: It's impossible to pass a float to printf.. - R.. 2012-04-04 01:27
Oops, I meant scanf(). But yeah, my question still holds - Mysticial 2012-04-04 01:27


3

Been a while since I did any coding in C, so you may want to confirm via experimentation, but all single-precision floats are valid double-precision floats, so you could just use '%lf' in the fscanf, store to a temporary double-precision float, and then use logic to assign it to the correct variable.

Alternatively, if you're using "#define"s, you could just 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]);
2012-04-04 01:26
by Ariel
Ads