4

I have a class which returns a typed pointer to a "const TCHAR". I need to convert it to a std::string but I have not found a way to make this happen.

Can anyone provide some insight on how to convert it?

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
TERACytE
  • 7,553
  • 13
  • 75
  • 111
  • Create a new std::string with the returned TCHAR as initial value: TCHAR xyz=fun(); string convertedforme(xyz); ? – Leonidas Jan 26 '10 at 19:08

4 Answers4

11

Depending on your compiling settings, TCHAR is either a char or a WCHAR (or wchar_t).

If you are using the multi byte character string setting, then your TCHAR is the same as a char. So you can just set your string to the TCHAR* returned.

If you are using the unicode character string setting, then your TCHAR is a wide char and needs to be converted using WideCharToMultiByte.

If you are using Visual Studio, which I assume you are, you can change this setting in the project properties under Character Set.

Brian R. Bondy
  • 339,232
  • 124
  • 596
  • 636
  • Here is what I did: #if !defined(UNICODE) || !defined(_UNICODE) const std::string k_Var ( reinterpret_cast (Var2.ReturnsAConstTCHAR())); #endif – TERACytE Jan 26 '10 at 22:19
  • Oops. That should read "static_cast" not "reinterpret_cast". – TERACytE Jan 26 '10 at 22:32
3

Do everything Brian says. Once you get it in the codepage you need, then you can do:

std::string s(myTchar, myTchar+length);

or

std::wstring s(myTchar, myTchar+length);

to get it into a string.

McBeth
  • 1,177
  • 8
  • 12
3

You can also use the handy ATL text conversion macros for this, e.g.:

std::wstring str = CT2W(_T("A TCHAR string"));

CT2W = Const Text To Wide.

You can also specify a code page for the conversion, e.g.

std::wstring str = CT2W(_T("A TCHAR string"), CP_SOMECODEPAGE);

These macros (in their current form) have been available to Visual Studio C++ projects since VS2005.

Rob
  • 76,700
  • 56
  • 158
  • 197
1

It depends. If you haven't defined _UNICODE or UNICODE then you can make a string containing the character like this:

const TCHAR example = _T('Q');
std::string mystring(1, example);

If you have are using _UNICODE and UNICODE then this approach may still work but the character may not be convertable to a char. In this case you will need to convert the character to a string. Typically you need to use a call like wcstombs or WideCharToMultiByte which gives you fuller control over the encoding.

Either way you will need to allocate a buffer for the result and construct the std::string from this buffer, remembering to deallocate the buffer once you're done (or use something like vector<char> so that this happens automatically).

CB Bailey
  • 755,051
  • 104
  • 632
  • 656