I wrote this program for getting a double input:
double n;
scanf("%lf",&n);
while(fgetc(stdin)!='\n')
return 0;
printf("%lf",n);
This program is supposed to take double as input. Provided that %lf
is the format specifier for double
in scanf
, I used it. But for inputs of a digit followed by e. ex.(3e), the input is being read without errors. But during processing of the same variable, it is discarding the e
and only considering 3
as is shown by the printf
statement. What is the cause of such behaviour?
Following the rationale given in defect report #22 (http://www.open-std.org/jtc1/sc22/wg14/docs/rr/dr_022.html), functions like scanf
(with %lf
) and strtod
should consume as much input as satisfies the expected format for the floating point constant. This means that they should consume the e
character in "3e"
even though the e
character is not followed by the actual exponent value (the exponent value is required to be present by 6.4.4.2).
This applies in equal degree to %lf
and %f
. In my experiments they behave exactly the same on this input. (Of course, %f
requires target variable of type float
.)
However, even after consuming both 3
and e
from the input stream, I would expect scanf
(and strtod
) to recognize "3e"
as an invalid representation of a floating point number (since, again, 6.4.4.2 requires the exponent value to be present) and act accordingly. In my experiment scanf
successfully read 3.0
. This I cannot explain yet.