Search code examples
c++wchar-tstring-conversion

wstringstream to LPWSTR


I have built up a string using wstringstream and need to assign it to a member of a struct of type LPWSTR. I try to use my_stringstream.str().c_str() but get the following compile time error:

cannot convert from 'const wchar_t *' to 'LPWSTR'

How can I do this? I have tried many different combinations of casts with either more compile time errors or random jargon when I try and display the string in a GUI.


Solution

  • Your function expects a pointer to modifiable data, i.e. wchar_t*, but the standard string class only exposes a pointer to constant. Assuming that your function may actually write to the memory, we need to provide it with a valid pointer.

    An easy way to obtain a modifiable buffer is, as always, a vector:

    std::vector<wchar_t> buf(mystring.begin(), mystring.end());
    buf.push_back(0);                 // because your consumer expects null-termination
    
    crazy_function(buf.data());
    crazy_function(&buf[0]);          // old-style
    
    // need a string again?
    std::wstring newstr(buf.data());  // or &buf[0]