0
votes

The following line of code is supposed to read a string, an int and two doubles separated by commas and store them in variables.

fscanf(f,"%[^,],%d,%Lf,%Lf",name,&id,&east, &north);

It works on my Visual Studio 2010 compiler and reads the right values. I've run the program on another machine on which I've got random values for the three numbers but the right value for the string.

What could it be?

1
The %Lf conversion specifier is for long double, not for double, %lf is for double.Daniel Fischer
%Lf is for long double not plain double. With Microsoft compilers, long double is the same size as double but other compilers have extended-size long doubles. I have no idea what's gone wrong with the int, unless id is in fact a long and you have a 32-bit/64-bit mismatch?Alan Curry
Why don't you guys post it as an answer? This most likely is the problem.orlp
OK, yeah, I sniped this one, but posting answers as a comment instead of an answer is really not proper use of SO...R.. GitHub STOP HELPING ICE
What was the operating system and compiler on the other machine? Did you check the return value from fscanf() so you know how many conversions worked? If fscanf() does not report 4, you've got a problem. Was the other compiler gcc? If so, what did it tell you when you enabled warnings with -Wall?Jonathan Leffler

1 Answers

1
votes

%Lf is for type long double, not double. On Microsoft compilers, long double has the same size and representation as double, so it happens to work, but your code is nonetheless invoking undefined behavior by using a mismatching format specifier. Use %lf with double, or change the type to long double if you want to use %Lf, and it should work everywhere.