dykw
dykw

Reputation: 1249

Read double using fscanf

I want to read double from text file e.g. 31 39.9316476397222 116.113516352222

I tried both, not work. I can only read the first few decimal digital e.g. 39.93164 but not 39.9316476397222 anyone knows why? Thanks!

int NodeID;
double _lat,_long;
fscanf (pFile, "%d %lf %lf", &NodeID,&_lat,&_long);
printf ("I have read: %d %f %f\n", NodeID,_lat,_long);

fscanf (pFile, "%d %lf %lf", &NodeID,&_lat,&_long);
printf ("I have read: %d %lf %lf\n", NodeID,_lat,_long);

Upvotes: 5

Views: 32063

Answers (2)

yzt
yzt

Reputation: 9113

I think the numbers are read correctly. Your problem is in your printing out, which makes you think you don't have the whole number. Keep in mind that printf typically only outputs a few digits after the decimal point.

I suggest you do these:

  1. In your printf calls, use a format specifier like this: "%.20f". It tells printf to output 20 digits after the decimal point.
  2. Keep in mind that whatever floating-point you use, float or double or long double, it's going to have a limited precision and resolution. Familiarize yourself with floating-point numbers and how they work and are represented.

Upvotes: 8

toddwz
toddwz

Reputation: 541

According to the fscanf man page, you should use %lf for double :

f, e, g (Floating point number) : A series of decimal digits, optionally containing a decimal point, optionally preceeded by a sign (+ or -) and optionally followed by the e or E character and a decimal integer (or some of the other sequences supported by strtod). Implementations complying with C99 also support hexadecimal floating-point format when preceded by 0x or 0X.
enter image description here

Upvotes: 22

Related Questions