Search code examples
c++chardoubletype-conversion

How to convert a double into a char*


I am heavily struggling with a question which should be very easy: how do I do a simple type conversion (from double into char*) in basic C.

I have found quite some solutions, but they are all based on conversions from double to char[x], but I am working here with char*, not with char[]. (I don't know how long the resulting string will be).
On top of that, I really can't believe that another type (be it stringstream, std::strings, ...) are needed for something that simple.

I admit, I'm a complete newbie in basic C, but I have worked in other languages (Visual Basic, Delphi, Java, ...) and I just can't understand why I can't find a simple function like "to_char_pointer(double d)" to do this.

Does anybody have an idea?


Solution

  • You can use sprintf() as you have done to convert a double into a string, but I would actually recommend using _snprintf() instead simply because sprintf() has no regard for the fact that strings are fixed length devices in memory and will overflow if you don't watch it. _snprintf() allows you to specify the length of the out string, just be sure to specify the size as one less than the actual allocated memory block, because _snprintf() does not store the terminating null character if it has to cut the output short.

    An example us using _snprintf() is:

    void ToString(char * outStr, int length, double val)
    {
         _snprintf(outStr,length,"%f",val);
    }