0

I have a function

void getXFromFile3(FILE* fptr){ double valueX; fscanf(fptr, "%lf\n", &valueX); printf("%lf", valueX); } 

and file data.dat with some double numbers.

One of them is -0.572869279, but my function print -0.572869. It looks like somewhere my number was cut off.

Any ideas what I am doing wrong?

10
  • 3
    Try printf("%.9lf", valueX); (or more) because the default is 6 places. Commented May 20, 2018 at 10:00
  • @WeatherVane But what if there are multiple doubles with different lengths after the decimal. We wouldn't want to print the extra zeros ( probably not the case here) and also what if it has greater than 9 digits say x digits? What then? Commented May 20, 2018 at 10:03
  • @Rishav OP does not say why he is printing them - perhaps to check he read them properly. If OP wants to reproduce the file data exactly, read with %s and store that as well as processing with sscanf. The answer was: Nothing wrong, the number read is not being cut off. Commented May 20, 2018 at 10:10
  • 1
    @Rishav if you want x places use printf("%.*lf", x, valueX); This is a non-question - it's all in the printf man page. Commented May 20, 2018 at 10:12
  • @WeatherVane Aah aight, thanks. Commented May 20, 2018 at 10:17

1 Answer 1

2

Tell scanf to tell you how many characters it scanned and then tell printf to print this number of digits after the comma.

Still one needs to take care of sign, and digits before the comma.

The code below assumes leading zeros and no positive signs were in the input.

void getXFromFile3(FILE* fptr){ double x; int n; fscanf(fptr, "%lf%n", &x, &n); printf("%.*lf", /* the l length modifier is optional */ n /* number of characters scanned */ - (x < 0.) /* one off for the minus sign, if any */ - ((int)log10(fabs(x)) + 1) /* off as many as digits before the comma */ - 1, /* one off for the comma */ x); } 

Hu! ;-)

Sign up to request clarification or add additional context in comments.

1 Comment

thanks! I don't need that to my program on studies I think, but still it is very interesting ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.