c++winapidoublelpcstr

double to const char * by function


R=10;
LPCSTR cs;
string s;
stringstream ss;
ss<<R;
s = ss.str();
cout << cs <<endl;

Will give me the console output 10, like it should be.

Now I wanted to put this into a function:

const char * doubleToLPSTR(double x){
string s;
stringstream ss;
ss << x;
s = ss.str();
return s.c_str();

}

But

R = 10;
LPCSTR cs;
string s;
cs = doubleToLPSTR(R);
cout << cs << endl;

Returns does not work.... Why???

Thank you for your help, like this?

const char * doubleToLPSTR(double x){

const int size = 20;
char *cs = new char[size];

string s;
stringstream ss;
ss << x;
s = ss.str();
const char * tempAr = s.c_str();


for (int i = 0; i < size; i++){

    cs[i] = tempAr[i];

}

return cs;
}

Solution

  • why don't you return a string from the function instead of char*? like:

    const string doubleToStr(double x){
      stringstream ss;
      ss << x;
      return ss.str();
    }
    
    R = 10;
    string s;
    s = doubleToStr(R);
    cout << s << endl;
    

    and if you really need a char*, you can use 's.c_str()' after the code above