I want to convert std::string into a const wchar_t *

后端 未结 4 1834
深忆病人
深忆病人 2020-11-28 08:44

Is there any method? My computer is AMD64.

::std::string str;
BOOL loadU(const wchar_t* lpszPathName, int flag = 0);

When I used:

相关标签:
4条回答
  • 2020-11-28 08:56

    First convert it to std::wstring:

    std::wstring widestr = std::wstring(str.begin(), str.end());
    

    Then get the C string:

    const wchar_t* widecstr = widestr.c_str();
    

    This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

    0 讨论(0)
  • 2020-11-28 09:00

    If you have a std::wstring object, you can call c_str() on it to get a wchar_t*:

    std::wstring name( L"Steve Nash" );
    const wchar_t* szName = name.c_str();
    

    Since you are operating on a narrow string, however, you would first need to widen it. There are various options here; one is to use Windows' built-in MultiByteToWideChar routine. That will give you an LPWSTR, which is equivalent to wchar_t*.

    0 讨论(0)
  • 2020-11-28 09:03

    You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:

    #include <atlconv.h>
    ...
    std::string str = "Hello, world!";
    CA2W pszWide(str.c_str());
    loadU(pszWide);
    

    You can also specify a code page, so if your std::string contains UTF-8 chars you can use:

    CA2W pszWide(str.c_str(), CP_UTF8);
    

    Very useful but Windows only.

    0 讨论(0)
  • 2020-11-28 09:10

    If you are on Linux/Unix have a look at mbstowcs() and wcstombs() defined in GNU C (from ISO C 90).

    • mbs stand for "Multi Bytes String" and is basically the usual zero terminated C string.

    • wcs stand for Wide Char String and is an array of wchar_t.

    For more background details on wide chars have a look at glibc documentation here.

    0 讨论(0)
提交回复
热议问题