3

As title states, I need a way to convert a PWCHAR to a std::string. The only solutions I can find online are for the opposite conversion, so I'd really like it if someone could shed some light on this. Thanks!

This is in c++.

user1553248
  • 1,184
  • 2
  • 19
  • 33

2 Answers2

2

According to this MSDN page, PWCHAR is declared as follows:

typedef wchar_t WCHAR, *PWCHAR;

What you want is std::wstring, declared in string.

const PWCHAR pwc;
std::wstring str(pwc);

std::wstring is very similar to std::string, as both are specializations of std::basic_string; the difference is in that wstring uses wchar_t (Windows WCHAR), whereas string uses char.


If you truly want a string (and not a wstring), the advised C++ way is to use use_facet as seen here:

const std::locale locale("C");
const std::wstring src = ...;
const std::string dst = ...;
std::use_facet<std::ctype<wchar_t> >(loc)
    .narrow(src.c_str(), src.c_str() + src.size(), '?', &*dst.begin());

You may also separately convert to a multibyte C string and then use this to build your std::string. This is not the preferred way of doing this in C++, however. The function for doing this is wcstombs, as declared below:

size_t wcstombs ( char * mbstr, const wchar_t * wcstr, size_t max );

Since you're on Windows, you may also use WideCharToMultiByte for this step.

int WideCharToMultiByte(
  __in       UINT CodePage,
  __in       DWORD dwFlags,
  __in       LPCWSTR lpWideCharStr,
  __in       int cchWideChar,
  __out_opt  LPSTR lpMultiByteStr,
  __in       int cbMultiByte,
  __in_opt   LPCSTR lpDefaultChar,
  __out_opt  LPBOOL lpUsedDefaultChar
);

LPSTR is defined as follows according to the MSDN:

typedef CHAR *LPSTR;
typedef char CHAR;
Community
  • 1
  • 1
obataku
  • 29,212
  • 3
  • 44
  • 57
1

You will have a much easier time using std::wstring, since that is also a wide-character string class. If you really want to use std::string, and convert from 2-byte characters to single- or multi-byte characters, you will need to use a function that does that conversion. wcstombs() is the ANSI C function for doing this. Your platform may provide alternatives.

jwismar
  • 12,164
  • 3
  • 32
  • 44