4

How to convert a std::wstring to a TCHAR*? std::wstring.c_str() does not work since it returns a wchar_t*.

How do I get from wchar_t* to TCHAR*, or from std::wstring to TCHAR*?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
esac
  • 24,099
  • 38
  • 122
  • 179
  • Please keep in mind that this is possible only if wstring contains only ANSI characters. Do not expect the result of the suggested solution to be a correct string at all times. In fact, if you have to do it, it probably means there's something wrong. See my answer here: http://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful/1855375#1855375 on how I believe this situation should be handled, by avoidance of TCHAR completely. – Pavel Radzivilovsky Dec 13 '09 at 06:25

6 Answers6

6

use this :

wstring str1(L"Hello world");
TCHAR * v1 = (wchar_t *)str1.c_str();
SaeidMo7
  • 1,214
  • 15
  • 22
4
#include <atlconv.h>

TCHAR *dst = W2T(src.c_str());

Will do the right thing in ANSI or Unicode builds.

Ferruccio
  • 98,941
  • 38
  • 226
  • 299
  • 1
    And you need `USES_CONVERSION;` in front of `W2T` otherwise it will complain: "error C2065: '_lpw' : undeclared identifier" etc. – Deqing May 24 '16 at 00:48
2

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
user224217
  • 41
  • 2
2

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.

tletnes
  • 1,958
  • 10
  • 30
1

You can use:

wstring ws = L"Testing123";
string s(ws.begin(), ws.end());
// s.c_str() is what you're after
rmn
  • 2,386
  • 1
  • 14
  • 21
0

Assuming that you are operating on Windows.

If you are in Unicode build configuration, then TCHAR and wchar_t are the same thing. You might need a cast depending on whether you have /Z set for wchar_t is a type versus wchar_t is a typedef.

If you are in a multibyte build configuration, you need MultiByteToWideChar (and vica versa).

bmargulies
  • 97,814
  • 39
  • 186
  • 310