%i, %d, %f ??

This is a discussion on %i, %d, %f ?? within the C++ Programming forums, part of the General Programming Boards category; I was just playing around with Win32 MessageBox and sprintf... when i noticed that when i try to put a ...

  1. #1
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483

    %i, %d, %f ??

    I was just playing around with Win32 MessageBox and sprintf... when i noticed that when i try to put a double into an array of chars with sprintf it messes up when i use %d or %i, but it works for ints.

    here is what i mean
    Code:
    int x = 1280;
    int y = 1024;
    double r = static_cast<double>(x)/static_cast<double>(y);
    char szBuffer[100];
    sprintf(szBuffer, "X: %i, Y: %i, R: %i", x, y, r);
    OUTPUT:
    X: 1280, Y: 1024, R: 0
    
    sprintf(szBuffer, "X: %d, Y: %d, R: %d", x, y, r);
    OUTPUT:
    X: 1280, Y: 1024, R: 0
    
    sprintf(szBuffer, "X: %d, Y: %d, R: %d", x, y, r);
    OUTPUT:
    X: 1280, Y: 1024, R: 1.250000
    i tried variations with all the letters in the alphabet and i got weird things like CCCCCCD or cccccd.

    Can anyone tell me what the %i is for and how its used and the %d and %f and any other ones if there are.

    Thanks
    My Website
    010000110010101100101011
    Add Color To Your Code!

  2. #2
    Registered User
    Join Date
    Nov 2004
    Location
    Slovenia, Europe
    Posts
    115
    http://si.php.net/sprintf
    It's for PHP, but I think there isn't much difference between PHP's sprintf() and sprintf() in C++
    [C++]
    IDE: DevC++ 4.9.9.2 (GCC 3.4.2)
    2nd compiler: g++ (GCC 3.4.3/4.0.0)
    3rd compiler: Borland 5.5
    [C#]
    IDE: Microsoft Visual C# Express 2005
    2nd IDE: SharpDevelop
    2nd compiler: csc in Command Prompt
    .NET Framework: 2.0
    [PHP]
    Core: 5.1.0 beta 3
    IDE: PHPEdit
    2nd IDE: Notepad
    Favourite extensions: exif,gd2,mysql
    Favourite PEAR packages: DB, XML_RSS, ID3
    Favourite databases: SQLite, MySQL

  3. #3
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,006
    FAQ > How do I... (Level 1) > Format output using printf() (C)
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,433
    The short answer to the original question is that %d and %i work for int types, but %f is for double types. Keep in mind that the ONLY information that the internals of functions like printf() receive about the type of arguments is what you provide in the format string. If you call
    Code:
    printf("%d\n", a_double);
    the internals of printf() receives no information that a_double is a double rather than an int.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21