LPWSTR to wstring c++

c++, wstring

Solution

No conversion or copying needed.

std::wstring nnWString(MAX_PATH, 0);
nnWString.resize(LoadStringW(hMod, id, &nnWString[0], nnWString.size());

Note: Your original code causes undefined behavior, because it writes using an uninitialized pointer. Surely not what you wanted.

Here's another variation:

- http://msmvps.com/blogs/gdicanio/archive/2010/01/05/stl-strings-loading-from-resources.aspx

Problem

I would like to read utf-8 test from a .dll string table. something like this ``` LPWSTR nnW; LoadStringW(hMod, id, nnW, MAX_PATH); ``` and after that I would like to convert the `LPWSTR nnW` to `std::wstring nnWstring`. I tried in this way: LPWSTR nnW; LoadStringW(hMod, id, nnW, MAX_PATH); ``` const int length = MultiByteToWideChar(CP_UTF8, 0, // no flags required (LPCSTR)nnW, -1, // automatically determine length NULL, 0); std::wstring nnWstring(length, L'\0'); if (!MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)nnW, -1, &nnWstring[0], length)) MessageBoxW(NULL, (LPCWSTR)nnWstring.c_str(), L"wstring", MB_OK | MB_ICONERROR); ``` After that in the MessageBoxW only shows the first letter.

Original source