2

I am trying to read in a double value continuously from the user using scanf.

Code:

printf("Enter A value: \n");
double input;
int result = scanf("%f", &input);
printf("INPUT: %f\n", input);

The output is

INPUT: 0.000
cadaniluk
  • 15,027
  • 2
  • 39
  • 67
code
  • 69
  • 1
  • 9

2 Answers2

8

You lied to the compiler: when scanning, %f says you supply a pointer to float. But you provided a pointer to double.

To fix, either use %lf or declare input as float.

Note that there is an asymmetry with printf formats, which uses %f for both float and double arguments. This works because printf arguments are promoted to double (and are not pointers).

Jens
  • 69,818
  • 15
  • 125
  • 179
3

I am trying to read in a double value continuously from the user using scanf.

To do so you need a loop, like the following:

while(scanf("%lf", &input) == 1) {
    //code goes here...
    printf("INPUT: %lf\n", input);
    //code goes here...
}

Note that, as the primitive type of input is double, you need to use %lf instead of %f (%fused for float).

mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • Should it be `!= EOF` or `== 1`? – Fiddling Bits Oct 21 '15 at 21:27
  • @FiddlingBits, you are correct, answer updated. [scanf returns the value of the macro EOF if an input failure occurs before any conversion. Otherwise, scanf returns the number of input items assigned, which can be fewer than provided for, or even zero, in the event of an early matching failure.](http://www.rowleydownload.co.uk/arm/documentation/index.htm?http://www.rowleydownload.co.uk/arm/documentation/scanf.htm) – mazhar islam Oct 21 '15 at 21:44