Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is there any method? My computer is AMD64.

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

When I used:

loadU(&str); 

the VS2005 compiler says:

Error 7 error C2664:: cannot convert parameter 1 from 'std::string *__w64 ' to 'const wchar_t *' 

How can I do it?

like image 245
user25749 Avatar asked Oct 29 '08 13:10

user25749


2 Answers

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.

like image 85
marijne Avatar answered Oct 18 '22 09:10

marijne


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*.

like image 29
Matt Dillard Avatar answered Oct 18 '22 08:10

Matt Dillard