Thread: Convert from float to char*

  1. #1
    Registered User
    Join Date
    Sep 2005
    Posts
    85

    Convert from float to char*

    Hello;

    I need to take a float value, which will always be a whole integer number, so can be cast with int(float) to become an int. I then need to het this int into a char* for a GL command. Can someone help?

  2. #2
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    you can use sprintf()
    Code:
    float n = 123;
    char buf[8];
    sprintf(buf,"%d", (int)n);
    I think this will work too
    Code:
    float n = 123;
    char buf[8];
    sprintf(buf,"%.0f", n);

  3. #3
    Registered User
    Join Date
    Sep 2005
    Posts
    85
    Can I do this without having to declare an array size for the char*

  4. #4
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Code:
    #include <sstream>
    
    std::stringstream Stream;
    Stream << static_cast<int>(var);
    const char* charPointer = Stream.str().c_str();
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Can I do this without having to declare an array size for the char*
    Arrays are not pointers.

    Code:
    float n = 123;
    char buf[8];
    sprintf(buf,"%d", (int)n);
    glSomeFunc( buf );
    The array becomes a char* (learn about how arrays decay into pointers to the first element of the array) when you pass the array as a function parameter.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. convert negative float to positive ???
    By manny in forum C Programming
    Replies: 4
    Last Post: 07-02-2009, 03:37 AM
  2. Replies: 2
    Last Post: 05-13-2009, 03:25 PM
  3. Opengl walking leg animation
    By Bobby230 in forum C Programming
    Replies: 3
    Last Post: 03-05-2006, 03:41 PM
  4. Display list not displaying?
    By psychopath in forum Game Programming
    Replies: 5
    Last Post: 09-19-2004, 06:47 PM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 11:58 AM