How to convert std::wstring to a TCHAR*?
Solution 1
#include <atlconv.h>
TCHAR *dst = W2T(src.c_str());
Will do the right thing in ANSI or Unicode builds.
Solution 2
use this :
wstring str1(L"Hello world");
TCHAR * v1 = (wchar_t *)str1.c_str();
Solution 3
TCHAR* is defined to be wchar_t* if UNICODE is defined, otherwise it's char*. So your code might look something like this:
wchar_t* src;
TCHAR* result;
#ifdef UNICODE
result = src;
#else
//I think W2A is defined in atlbase.h, and it returns a stack-allocated var.
//If that's not OK, look at the documenation for wcstombs.
result = W2A(src);
#endif
Solution 4
in general this is not possible since wchar_t may not be the same size as TCHAR.
several solutions are already listed for converting between character sets. these can work if the character sets overlap for the range being converted.
I prefer to sidestep the issue entirely wherever possible and use a standard string that is defined on the TCHAR character set as follows:
typedef std::basic_string<TCHAR> tstring;
using this you now have a standard library compatible string that is also compatible with the windows TCHAR macro.
Solution 5
You can use:
wstring ws = L"Testing123";
string s(ws.begin(), ws.end());
// s.c_str() is what you're after
esac
I am a software developer primarily focused on WinForms development in C#. I have been in development for 10 years.
Updated on June 09, 2022Comments
-
esac almost 2 years
How to convert a
std::wstring
to aTCHAR*
?std::wstring.c_str()
does not work since it returns awchar_t*
.How do I get from
wchar_t*
toTCHAR*
, or fromstd::wstring
toTCHAR*
?