Use a std::wstring
:
LPWSTR a = L"check";
std::wstring b = a;
Explanation.
Is there a simple way to convert a LPWSTR
into a string
?
There is not. They are incompatible types. The first is a pointer pointing to a memory area that contains a series of characters while the second is a class that internally manages a dynamic memory buffer that contains characters but also offers operations to query and modify that buffer.
To put an analogy: it would be like trying to convert a transistor into a radio; While it is true that radios contain transistors, a radio is much more than a collection of transistors in the same way that a string
is much more than a collection of characters.
But luckily you can build a string
using the data pointed to by LPWSTR
; in practice you will not have transformed the LPWSTR
in string
if not that you will have two different data but with the same content.
Build a string
from a LPWSTR
.
You have indicated that LPWSTR
is ...
I understand that a LPWSTR
is a long pointer to a constant string
.
But this is not entirely true. To begin with, it is not a pointer to a constant string (that's the LPCWTSTR
, note that it contains a C
to indicate that it is constant). According to Microsoft documentation LPWSTR
is a pointer alias to WCHAR
which in turn is an alias of the basic type wchar_t
:
typedef wchar_t WCHAR;
typedef WCHAR *LPWSTR;
So deep down, a LPWSTR
is simply wchar_t *
and the library of standard templates has a class string
that manages data of that type and is consequently buildable with them.
The template class std::basic_string
can manage strings of different widths and encodings depending on how it is configured:
-
std::basic_string<char>
for normal characters, has the alias std::string
.
-
std::basic_string<wchar_t>
for wide characters, has the alias std::wstring
.
-
std::basic_string<char16_t>
for characters UTF-16 , has the alias std::u16string
.
-
std::basic_string<char32_t>
for characters UTF-32 , has the alias std::u32string
.
Knowing this, we can construct a string
from a LPWSTR
in the following way:
LPWSTR a = L"check";
std::wstring b = a;