Convert from float to char*

This is a discussion on Convert from float to char* within the C++ Programming forums, part of the General Programming Boards category; Hello; I need to take a float value, which will always be a whole integer number, so can be cast ...

  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 wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,755
    > 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, 04:37 AM
  2. Replies: 2
    Last Post: 05-13-2009, 04: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, 07:47 PM
  5. Half-life SDK, where are the constants?
    By bennyandthejets in forum Game Programming
    Replies: 29
    Last Post: 08-25-2003, 12:58 PM

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