double to const char * by function

3k Views Asked by At
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;
}
4

There are 4 best solutions below

7
On BEST ANSWER

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

1
On

By the looks of it, the return value doesn't really need to be a char* - you are just outputting the return value after all - which means that you could use a string. (That is, of course there is a reason it needs to be a char* that you have omitted for brevity?)

Rather than having to convert the double to a string yourself then you can use the String class which has a method "std::to_string()" which can convert all numeric types, including double.

More information on that can be found here.

But the basic usage in your case would be...

R = 10;
std::cout << std::to_string(R) <<std::endl;
0
On

Variable string s is a local variable in function doubleToLPSTR.

During runtime, once you're "out of" this function, this variable is destroyed.

So with return s.c_str(), you are essentially invoking undefined behavior.

The outcome of any attempt to access the returned address would be inconsistent.

0
On
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;
}

And then in the program:

R = 10;
const char *cs = doubleToLPSTR(R);
cout << cs << endl;

And I needed it because i nee a LPCSTR in

CreateWindow("STATIC", cs, WS_VISIBLE | WS_CHILD | SS_RIGHT, xSC, top, bS, hEaS,
    hwnd, NULL, hInstance, NULL);