Thursday, January 17, 2008

C++ scanf and fscanf woes


I have been doing a whooping lot of C++ coding recently and one of the things that irked me the most was the scanf/fscanf function. For starters, one can write out double type variables to the fprintf and printf functions. Assuming that, since this can be done, I attempted to use fscanf to read double types from a file. As it turns out the double types cannot be read -- no value is stored in the double variable.

Why? Well apparently the scan functions can only read float types with the "%f" mask. So a float variable is required to read the float and then a static cast must be performed to turn it into a double. To read a double the mask should be "%lf". The most hard to detect part is the compiler accepts a double type as a legitimate type for the scanf/fscanf functions, so some form of warnings must be switched on to detect that. To further complicate things, printf functions use "%f" to print doubles.

2 comments:

viduka said...

HELLO. time to reduce number of posts showing on 1st page lah... make my firefox hang lor loading your page..

Devil said...

ops haha, ok halved it.