Convert TCHAR array to char array
Asked Answered
M

4

14

How to convert to TCHAR[] to char[] ?

Mai answered 24/11, 2009 at 10:40 Comment(3)
Duplicate: #159942Deliquesce
This will definitely help you:codeproject.com/Articles/76252/…Benbow
I just change General -> Character Set := "Use Unioncode Character set" and its now working (char *) tcharr ;Orcein
S
12

Honestly, I don't know how to do it with arrays but with pointers, Microsoft provides us with some APIs, such as wctomb and wcstombs. First one is less secure than the second one. So I think you can do what you want to achieve with one array-to-pointer and one pointer-to-array casting like;

// ... your includes
#include <stdlib.h>
// ... your defines
#define MAX_LEN 100
// ... your codes
// I assume there is no any defined TCHAR array to be converted so far, so I'll create one
TCHAR c_wText[MAX_LEN] = _T("Hello world!");
// Now defining the char pointer to be a buffer for wcstomb/wcstombs
char c_szText[MAX_LEN];
wcstombs(c_szText, c_wText, wcslen(c_wText) + 1);
// ... and you're free to use your char array, c_szText

PS: Could not be the best solution but at least it's working and functional.

Samualsamuel answered 19/12, 2012 at 1:56 Comment(0)
L
5

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().

Logarithmic answered 24/11, 2009 at 10:48 Comment(1)
I think we need to convert from wchar_t to char so we need WidecharToMultiByte!!Pompous
A
3

Why not just use wcstombs_s ?

Here is the code to show how simple it is.

#define MAX_LENGTH 500
...

TCHAR szWideString[MAX_LENGTH];
char szString[MAX_LENGTH];
size_t nNumCharConverted;
wcstombs_s(&nNumCharConverted, szString, MAX_LENGTH,
        szWideString, MAX_LENGTH);
Acosmism answered 3/6, 2017 at 4:4 Comment(3)
You misspelled 'LENGTH'.Criticism
LENGHT is a constant not a keyword.Enthral
Done, I fixed LENGTH spelling.Acosmism
P
2

It depends on the character set (Unicode or ANSI) (wchar_t or char), so if you are using ANSI simply TCHAR will be char without any casting, but for Unicode, you have to convert from wchar_t to char, you can use WideCharToMultiByte

Pompous answered 24/11, 2009 at 10:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.