0

C++ code for double using cstdio header.

#include <cstdio>
    using namespace std;
    
    int main() {
    
            double f;
            scanf("%lf",&f);
            printf("%lf",f);
            
            return 0;
    }

This code always output 0.000000. Why? But similar code works well in C

#include<stdio.h>

    int main() {
            double f;
            scanf("%lf",&f);
            printf("%lf",f);
            return 0;
    }

This code works Fine.

GIRISH kuniyal
  • 740
  • 1
  • 5
  • 14
  • 4
    `printf("%lf",f);` --> `printf("%f",f);` – Sourav Ghosh Nov 12 '16 at 13:19
  • 3
    Can't reproduce: http://ideone.com/MsqXCs - Could you please tell which compiler you're using, and which input data you test with ? – Christophe Nov 12 '16 at 13:23
  • 2
    Code working in ideone doesn't prove anything in the general case. `long double` and `double` may or may not have different representation in a particular execution environment. – Roland Illig Nov 12 '16 at 13:27
  • 2
    an exact duplicate: [Correct format specifier for double in printf](http://stackoverflow.com/q/4264127/995714) – phuclv Nov 13 '16 at 13:31
  • this is codeblocks compiler.. I don't know why this happen. but i am unable to reproduce on another PC and online ide. – GIRISH kuniyal Nov 14 '16 at 08:33
  • 1
    using the wrong format specifier invokes undefined behavior. The fact that it works on 1 or 2 computers doesn't mean that it'll work on others – phuclv Nov 14 '16 at 08:45

1 Answers1

1

Read the documentation of fscanf and fprintf (especially the conversion specifiers, they differ) and remove the using namespace std.

Roland Illig
  • 40,703
  • 10
  • 88
  • 121