What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)?

46,717

Solution 1

MultiByteToWideChar but also see "A few of the gotchas of MultiByteToWideChar".

Solution 2

The simplest way is to use the conversion macros:

  • CW2A
  • CA2W
  • etc...

MSDN

Solution 3

TCHAR is a Microsoft-specific typedef for either char or wchar_t (a wide character).

Conversion to char depends on which of these it actually is. If TCHAR is actually a char, then you can do a simple cast, but if it is truly a wchar_t, you'll need a routine to convert between character sets. See the function MultiByteToWideChar()

Solution 4

There are a few answers in this post as well, especially if you're looking for a cross-platform solution:

UTF8 to/from wide char conversion in STL

Solution 5

Although in this particular situation I think the TChar is a wide character I'll only need to do the conversion if it isn't. which I gotta check somehow.

if (sizeof(TCHAR) != sizeof(wchar_t))
{  .... }

The cool thing about that is both sizes of the equals are constants, which means that the compiler will handle (and remove) the if(), and if they are equal, remove everything inside the braces

Share:
46,717
Ambuj Mehra
Author by

Ambuj Mehra

I enjoy writing software. I am currently working on Android hybrid apps for retail in store devices as well as some Websphere Commerce.

Updated on July 09, 2022

Comments

  • Ambuj Mehra
    Ambuj Mehra almost 2 years

    This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar.