Блог пользователя luyi0619

Автор luyi0619, 12 лет назад, По-английски

I found that "lf" is ok for GNU C++ and MS C++, but not ok for C++ 0x using printf. Also, "f" works well for them.

float and double both use "f" ?

How about scanf ?

Could any body offer me some references?

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
12 лет назад, # |
  Проголосовать: нравится +7 Проголосовать: не нравится

%f is for float only. %lf is for double. It's both for scanf and printf.

  • »
    »
    12 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    however, if you use lf for double in c++ 0x , it does not work.

    • »
      »
      »
      12 лет назад, # ^ |
      Rev. 2   Проголосовать: нравится 0 Проголосовать: не нравится

      If you use GCC, you can add -D__USE_MINGW_ANSI_STDIO=0 parameter to compilation command line and %lf will work quite OK.

»
12 лет назад, # |
Rev. 2   Проголосовать: нравится +6 Проголосовать: не нравится

To operate on double, use %f or %lf with printf(), but only %lf with scanf(). Reference: the C99 standard, 7.19.6.1.7, 7.19.6.1.8 and 7.19.6.2.11. C++11 is based on C99 (1.1.2) and includes its standard library (17.2, 27.9.2). So the same format must work for C++11, too.

If it does not work, then your C++ implementation might not be fully conformant.

»
12 лет назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Usually it's enough to print float, You may cat double to float and use %f, which usually works fine

»
12 лет назад, # |
Rev. 3   Проголосовать: нравится 0 Проголосовать: не нравится

Traditionally, only %f can be used in printf for printing doubles and floats. The main idea is that when passing any floating-point numbers (float or double) to variadic functions like printf they are automatically promoted to double, so you don't have to (or can't) distinguish double from float and only one format specifier is used in printf. But this confused some people, so the new version of C (but not the current version of C++) allows the use of %lf for doubles in printf.

»
12 лет назад, # |
Rev. 3   Проголосовать: нравится +3 Проголосовать: не нравится

There is slow, but simple method:

float f;
cin >>f;

double d;
cin >>d;

long double ld;
cin >>ld;

int i;
cin >>i;

long long ll;
cin >>ll;

string s;
cin >>s; //this type of reading without spaces

char c;
cin >>c;