Convert LPWSTR to string

1

How could I convert a LPWSTR(Long Pointer Wide String) to string. I understand that an LPWSTR is a long pointer to a constant string. But there is some simple way to convert an LPWSTR eg:

LPWSTR a = L"check";

A string:

string b = // la conversión

How could I do it since it can be iterated and many ways but I still have difficulties.

    
asked by Sergio Ramos 21.03.2017 в 12:58
source

2 answers

1

You can use the CW2A macro. An example:

#include "atlstr.h"

LPWSTR a = L"check";
std::string b = CW2A(a);

More information on the MSDN

    
answered by 21.03.2017 в 13:05
1

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;
    
answered by 22.03.2017 в 10:47