在cpp中将字符串转换为_T

yog*_*ogi 4 c++ windows

我想转换string或者char*_T,但无法做到.

如果我写

_tcscpy(cmdline,_T ("hello world")); 
Run Code Online (Sandbox Code Playgroud)

它完美无缺,但如果我写的话

char* msg="hello world";
_tcscpy(cmdline,_T (msg));
Run Code Online (Sandbox Code Playgroud)

它显示如下错误: error C2065: 'Lmsg' : undeclared identifier

请给我一个解决方案.

Thanx提前.

Naw*_*waz 10

_T是一个宏,定义为(如果UNICODE已定义):

#define _T(a)  L ## a
Run Code Online (Sandbox Code Playgroud)

这只能用于字符串文字.因此,当你写_T("hi")它时L"hi",它变得有效,如预期的那样.但是当你写_T(msg)它时Lmsg,它变成了一个未定义的标识符,你并不打算这样做.

您只需要这个功能mbstowcs:

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;
Run Code Online (Sandbox Code Playgroud)