-2

I usually need to convert a CHAR or CHAR* to a TCHAR or TCHAR*

CHAR chDecimal = 'A';
TCHAR Decimal = '\0';
int written = MultiByteToWideChar(CP_ACP, 0, &chDecimal, 1, &Decimal, 1);  
std::wcout << Decimal << endl;
getchar();

Is there a better and fastest way to do it without using ATL or other Microsoft libraries? Thank you.

  • Did you try to write something faster? Did you measure it? – πάντα ῥεῖ Mar 01 '15 at 11:54
  • 1
    For THIS VERY CASE, `Decimal = chDecimal;` will do what you want. Of course, problem comes if `char chDecimal[] = "\xc2\xb0";` - but then your code won't work either. – Mats Petersson Mar 01 '15 at 11:58
  • Why do you think you need to convert, `wchar_t`-based streams can handle `char`, too? That's also the reason the above code is correct, as it writes a `TCHAR`-based string to `std::wcout`, but I wonder if that shouldn't be a `wchar_t`-based string instead? One more advise: Avoid `TCHAR`, if possible. Also, avoid plain `CHAR` if it is text that uses more than just the basic ASCII, use `wchar_t` or `WCHAR` instead. – Ulrich Eckhardt Mar 01 '15 at 12:06
  • You mean because the fixed lenght to 1? – novice_cplusplus Mar 01 '15 at 12:08

1 Answers1

3

The code presented in the question,

CHAR chDecimal = 'A';
TCHAR Decimal = '\0';
int written = MultiByteToWideChar(CP_ACP, 0, &chDecimal, 1, &Decimal, 1);

does not convert to TCHAR (which depends on whether UNICODE is defined), as is claimed. Instead it unconditionally converts to wchar_t. Also, using the Microsoft T stuff, which is in support of Windows 9x and which was obsolete already in the year 2000 with the introduction of Layer for Unicode, is extremely dubious practice for non-legacy code.

Converting single encoding points is anyway a very dubious practice. It fails for any encoding scheme with more than one byte per character, such as Japanese codepages, or UTF-8.

If the intent is to convert only ASCII characters, then just copy it, using either the C++ copy assignment operator = or initialization. Can't get simpler than that.

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331