Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

C++, format spec for getting double with scanf(..)?

This code doesn't get num correctly:

double num;

printf("\nEnter the number: ");

scanf("%f",&num);

but changing to

float num;

and it works fine!

What is the format spec for a double? cplusplus.com doesn't have an answer.

Thanks

Update:

Thanks guys. Also, I know that there's a (long double) cast. What's the format spec for printing a long double?

Update 2:

Thanks Cubbi. I always learn a lot from your answers. And yes, C++ is fun! Can you send me a reference to this C standard of which you speak? I use cplusplus.com as my reference and it's either not there or I missed it.

2 Answers

Relevance
  • ?
    Lv 7
    1 decade ago
    Favorite Answer

    My compiler helpfully gives a diagnostic on your program:

    test.cc:6:16: warning: format '%f' expects type 'float*', but argument 2 has type 'double*'

    Since this is a C function, the C++ language standard simply refers to the C language standard, which says, under 7.19.6.2:

    l (ell)

    Specifies that [...] a following a, A, e, E, f, F, g, or G conversion specifier applies to

    an argument with type pointer to double

    So, use %lf

  • oops
    Lv 6
    1 decade ago

    "%Lf"

    Long float

    Edit: My mistake, lf is for doubles, LF is for long doubles. Lf worked for me because my compiler doesn't distinguish between the two.

    Lf should work for printing long doubles.

Still have questions? Get your answers by asking now.