Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to _T in cpp

Tags:

c++

windows

I want to convert string or char* to the _T but not able to do.

if i write

_tcscpy(cmdline,_T ("hello world")); 

it works perfectly, but if i write

char* msg="hello world";
_tcscpy(cmdline,_T (msg));

it shows an error like: error C2065: 'Lmsg' : undeclared identifier

Please give me a solution.

Thanx in advance.

like image 258
yogi Avatar asked Nov 30 '22 08:11

yogi


2 Answers

_T only works with string literals. All it does is turn the literal into an L"" string if the code's being compiled with Unicode support, or leave it alone otherwise.

Take a look at http://msdn.microsoft.com/en-us/library/dybsewaf(v=vs.80).aspx

like image 29
NPE Avatar answered Dec 05 '22 05:12

NPE


_T is a macro, defined as (if UNICODE is defined):

#define _T(a)  L ## a

which can work only with string-literals. So when you write _T("hi") it becomes L"hi" which is valid, as expected. But when you write _T(msg) it becomes Lmsg which is an undefined identifier, and you didn't intend that.

All you need is this function mbstowcs as:

const char* msg="hello world"; //use const char*, instead of char*
wchar_t *wmsg = new wchar_t[strlen(msg)+1]; //memory allocation
mbstowcs(wmsg, msg, strlen(msg)+1);

//then use wmsg instead of msg
_tcscpy(cmdline, wmsg);

//memory deallocation - must do to avoid memory leak!
 delete []wmsg;
like image 63
Nawaz Avatar answered Dec 05 '22 06:12

Nawaz