-1

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?

alk
  • 69,737
  • 10
  • 105
  • 255
Dominique
  • 16,450
  • 15
  • 56
  • 112
  • The better question is what are you trying to do? A double cannot be converted to a char*. If you're simply trying to get a string representation of the double, you're going to have to convert it to a char array. A function accepting a char* will accept a char[]. – Christopher Schneider Aug 26 '15 at 14:50
  • Sorry, I was quite stressed when I wrote this question: it seems that I have access to STL library and as such my problem has been solved: `#include `
    `using namespace std;`

    `string str = to_string((long double)vector_with_doubles->at(i));`
    Hence this question can indeed be closed.
    – Dominique Aug 27 '15 at 07:06

1 Answers1

0

You can use sprintf() as you have done to convert a double to 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);
    }
Man Person
  • 1,122
  • 8
  • 20
  • 34
  • Using `snprintf()` (standard C function) rather than `_snprintf()` (non-standard C function) is certainly more portable. Using either instead of `sprintf()` to prevent overrun is a good first step, but checking the function's result and handling that is a necessary part missing here. – chux - Reinstate Monica Aug 26 '15 at 15:05