Thread: %i, %d, %f ??

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

    %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
    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);
    X: 1280, Y: 1024, R: 0
    sprintf(szBuffer, "X: %d, Y: %d, R: %d", x, y, r);
    X: 1280, Y: 1024, R: 0
    sprintf(szBuffer, "X: %d, Y: %d, R: %d", x, y, r);
    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.

    My Website
    Add Color To Your Code!

  2. #2
    Registered User
    Join Date
    Nov 2004
    Slovenia, Europe
    It's for PHP, but I think there isn't much difference between PHP's sprintf() and sprintf() in C++
    IDE: DevC++ (GCC 3.4.2)
    2nd compiler: g++ (GCC 3.4.3/4.0.0)
    3rd compiler: Borland 5.5
    IDE: Microsoft Visual C# Express 2005
    2nd IDE: SharpDevelop
    2nd compiler: csc in Command Prompt
    .NET Framework: 2.0
    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
    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
    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
    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
Website Security Test