How to convert std :: string to LPCWSTR in C ++ (Unicode)

I am looking for a method or code snippet to convert std :: string to LPCWSTR

+103
c ++ winapi
Aug 26 2018-08-08T00:
source share
7 answers

Thanks for the link to the MSDN article. This is exactly what I was looking for.

std::wstring s2ws(const std::string& s) { int len; int slength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len); std::wstring r(buf); delete[] buf; return r; } std::wstring stemp = s2ws(myString); LPCWSTR result = stemp.c_str(); 
+118
Aug 26 '08 at 2:36
source share

The solution is actually much simpler than any other suggestion:

 std::wstring stemp = std::wstring(s.begin(), s.end()); LPCWSTR sw = stemp.c_str(); 

Best of all, it is platform independent. h2h :)

+98
Nov 09 '10 at 23:12
source share

If you are in an ATL / MFC environment, you can use the ATL conversion macro:

 #include <atlbase.h> #include <atlconv.h> . . . string myStr("My string"); CA2W unicodeStr(myStr); 

Then you can use unicodeStr as LPCWSTR. The memory for the unicode string is created on the stack and freed, then the destructor for unicodeStr is executed.

+8
26 Aug 26 '08 at 2:30
source share

You can use CString as an intermediate:

 std::string example = "example"; CString cStrText = example.c_str(); LPTSTR exampleText = cStrText.GetBuffer(0); 
0
Dec 07 '17 at 20:20
source share

Instead of using std :: string, you can use std :: wstring.

EDIT: Sorry, this is inexplicable, but I have to run.

Use std :: wstring :: c_str ()

-one
Aug 26 '08 at 1:52
source share

LPCWSTR lpcwName = std :: wstring (strname.begin (), strname.end ()). C_str ()

-one
Apr 19 '19 at 9:31
source share
 string myMessage="helloworld"; int len; int slength = (int)myMessage.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, myMessage.c_str(), slength, buf, len); std::wstring r(buf); std::wstring stemp = r.C_str(); LPCWSTR result = stemp.c_str(); 
-2
Jan 20 '17 at 7:05
source share



All Articles