How are you?
I have written a script for a 32-bit machine (Ubuntu). I'm now compiling it for a 64-bit machine (RedHat). My code doesn't work and I have narrowed the reason down to fscanf() and fprintf() functions.

This is my 32-bit version which works:

float readFloat=0.0;
fscanf(myfile,"%f", &readFloat);
fprintf(newfile,"%f\n", readFloat);

On 64-bit I only get 0.0 back. They say that for 64 you should use %lf (long float). However I don't know how to declare long float, I only know double or long double.

This also works on 32-bit:

double readFloat=0.0;
fscanf(myfile,"%lf", &readFloat);
fprintf(newfile,"%lf\n", readFloat);

However, again this won't work on 64-bit. What is the right way to do it so that it would work on both 32 and 64-bit? If this is impossible, how to do it correctly on 64-bit alone?

Also, do I only need to worry about the floating point when going from 32-bit to 64-bit, or also the int.

Thanks so much.

> What is the right way to do it so that it would work on both 32 and 64-bit?

When printing out a float or a double value with the printf family of functions, always use %f

When reading in a a float value with the scanf family of functions, use %f; for reading a double use %lf.

The above applies to all platforms.

float f ;
scanf( "%f", &f ) ;

double d ;
scanf( "%lf", &f ) ;

Of course you can elide this entire issue by using C++ streams and formatted input/output - they provide robust and type-safe mechanisms to write or read data.

Brief Explanation (from c-faq.com)

Due to the ``default argument promotions'' (which apply in variable-length argument lists such as printf's, whether or not prototypes are in scope), values of type float are promoted to double, and printf therefore sees only doubles. (printf does accept %Lf, for long double.)

scanf, on the other hand, accepts pointers, and no such promotions apply. Storing into a float (via a pointer) is very different from storing into a double, so scanf distinguishes between %f and %lf. %f tells scanf to expect a pointer-to-float, and %d tells it to expect a pointer-to-double.

(Strictly speaking, %lf is undefined under printf, though many systems probably accept it. To be portable, always use %f.)


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2017 About.com. All rights reserved.