1

I can't scan a double to a variable.

This is my code, it is very simple. I built it with command:

gcc -Wall -Wextra -Wpedantic -ansi -c double.c

#include <stdio.h>
int main() {
    double f;
    scanf("%lf", &f);
    printf("%lf\n", f);
    return 0;
}

Input: 5.5 (or any other numbers)

Output: 0 (always)

I am using (GCC) 4.9.3.

mja
  • 1,273
  • 1
  • 20
  • 22
  • 1
    Your code is perfectly fine in modern C (and has been fine since 1999). However, you are apparently compiling it in archaic C89/90 mode. Back then `printf` did not support `%lf` format. Note, your version is actually *preferable*, but you have to remember that historical peculiarity. The real question is: why are you compiling in archaic mode? – AnT stands with Russia May 07 '16 at 19:45
  • @AnT I didn't know that. But why gcc don't set up C99 mode by default? – mja May 07 '16 at 19:53
  • 1
    GCC as finally switched to C11-based dialect of C as default one just about a month (or a few months) ago. Before that they were devotedly sticking to C89/90 for legacy code compatibility reasons or something like that. – AnT stands with Russia May 07 '16 at 19:57

1 Answers1

1

Read the compiler warning and fix it.

~$ gcc -Wall -Wextra -Wpedantic -ansi -c mydouble.c 
mydouble.c: In function ‘main’:
mydouble.c:5:12: warning: ISO C90 does not support the ‘%lf’ gnu_printf format [-Wformat=]
     printf("%lf\n", f);

You can change the compiler flag or change the code.

#include <stdio.h>
int main() {
    double f;
    scanf("%lf", &f);
    printf("%f\n", f);
    return 0;
}
Niklas Rosencrantz
  • 25,640
  • 75
  • 229
  • 424