Is there any difference in using %f, %e, %g, %E or %G with scanf?

lee77 picture lee77 · Nov 10, 2013 · Viewed 32.8k times · Source

In C, is there any difference in the format specifiers %f, %e, %g, %E and %G when used to read into a float variable with scanf? That is, will the behaviour of the code snippet

float x;
scanf("%<one of f, e, g, E, G>", &x);

ever depend on the choice of the specifier?

I first supposed that %f would only interpret decimal notation correctly, and %e would only interpret scientific notation correctly, but on my system, each of them works fine in either case. But maybe my system is just liberal...

I couldn't find any definite statement about this in my books or on the web...

Answer

Martin R picture Martin R · Nov 10, 2013

The above answer refers to C++, but the same is true for C.

From "7.19.6.2 The fscanf function" in the "Final version of the C99 standard with corrigenda TC1, TC2, and TC3 included, formatted as a draft" (link copied from http://en.wikipedia.org/wiki/C99):

a,e,f,g
Matches an optionally signed floating-point number, infinity, or NaN, whose format is the same as expected for the subject sequence of the strtod function. The corresponding argument shall be a pointer to floating.

The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

So %f, %e, %g, %E, %G all behave identically when scanning numbers, as you experienced.