I am a beginner at Winapi and I am trying to convert wstringstream to LPCWSTR like this (inside WM_PAINT):
wstringstream ws;
ws << "my text" << endl;
LPCWSTR myWindowOutput = ws.str().c_str();
hdc = BeginPaint(hWnd, &ps);
TextOut(hdc, 150, 305, myWindowOutput, 10);
It only produces rubbish though, can somebody help? Thank you.
LPCWSTR myWindowOutput = ws.str().c_str()
produces a temporary (the return value of the str() call), that's gone as soon as the full statement ends. Since you need the temporary, you need to move it down to the call, that eventually consumes it:Again, the temporary lives until the full statement ends. This time around, this is long enough for the API call to use it.
As an alternative, you could bind the return value of
str()
to a const reference1), and use that instead. This may be more appropriate, since you need to use the return value twice (to get a pointer to the buffer, and to determine its size):1) Why this works is explained under GotW #88: A Candidate For the “Most Important const”.