I have searched on the internet for a 'working' double to char* does anyone have any idea? I need to pass the string to a function that takes a char* as an argument.

You could try something like this:

#include <iostream>
#include <sstream>
#include <limits>
#include <iomanip>

std::string double_to_string(const double value)
{
    std::ostringstream stream;

    // Go for maximum precision and take into account that converting could fail.
    if (!(stream << std::setprecision(std::numeric_limits<double>::digits10) << value))
    {
        // Possibly throw an exception instead.
        return std::string();
    }

    return stream.str();
}

int main()
{
    std::cout << "Char* array: " << double_to_string(12.345678).c_str() << std::endl;

    return 0;
}

If you use the boost libraries you could use "lexical_cast" too. You could also convert it C-Style using sscanf / sprintf. A little performance comparison that was provided on the boost website: http://www.boost.org/doc/libs/1_47_0/libs/conversion/lexical_cast.htm#performance

Edited 4 Years Ago by Gonbe: Modified code to include precision.

ok I can use to_string() but how do I pass it to void fn(char* cText); ?I tried to read in the characters of the string in 1 at a time but its not working please can you help?

#include <iostream>
#include <sstream>

using namespace std;

void fn(char* s)
{
    cout << s << endl;
}

char* String2Char(string mystring)
{
    char* cText = "                                           ";
    static int num = 0;
    string::iterator it;
    for (it = mystring.begin(); it < mystring.end(); it++)
    {
        cText[num] = it[num];// <-- Unhandled exception at 0x0038DFF5 in 
                             // Project1.exe: 0xC0000005: Access 
                             // violation writing location 0x003A01E8.      
        num++;
    }

    return cText;
}

// this function round up to the last 4 or 5 digits
// use to_string instead
string convertDouble(double value) 
{
  std::ostringstream o;
  if (!(o << value))
    return "";
  return o.str();
}

int main ()
{
    char* s, s2;
    float fVal     = 3.1459867655f;
    string astring = "This is a string. ";

    s = "Passed string. ";

    fn(String2Char(to_string(fVal)));

    fn(s);


    astring += "This is the converted float ->" + to_string(fVal);

    cout << astring << endl;

    cin.get();
    return (1);
}

You can pass a string to a function that needs a char * by using the c_str() method of the string class. the c_str() function returns a const char * that holds what the string contains. in order for this to work the function you are passing the string into needs to except a const char * instead of a normal char *.

Thanks I just figured it out now aswell. I'll do this...

char c[80];
string s;
s = to_string(0.0158f);
strcpy_s(c, s.c_str());
fn(c);
This question has already been answered. Start a new discussion instead.