convert string to _T in cpp
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.
_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;
_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
You need to use mbtowcs function.
You should also look at this article.
_T
is a macro that makes string literals into wide-char string literals by prepending an L
before the literal in UNICODE
builds.
In other words, when you write _T("Hello")
it is as if you had written "Hello"
on an ANSI build or L"Hello"
on a UNICODE build. The type of the resulting expression is char*
or wchar_t*
respectively.
_T
can not convert a string variable (std::string
or char*
) to a wchar_t*
-- for this, you have to use a function like mbstowcs
or MultiByteToWideChar
.
Suggestion: It will be much easier for you (and in no way worse) to always make a UNICODE build and forget about _T
, TCHAR
and all other T
-derivatives. Just use wide-character strings everywhere.
_T
is not an actual type. It's a macro that prepends string literals with L
so that they would be wchar_t*
s instead of char*
. If you need to convert a char*
string to wchar_t*
one at runtime, you need mbtowcs for example.
The _T modifier is just a declaration to tell the compiler that the string literal must be interpreted as a utf-16 encoding. The reason it doesn't work on the variable is because the contents of that variable have already been declared as ascii.
As already mentioned the mbstowcs function is what you need to perform the conversion of a char data into utf-16 (wide char) data.
精彩评论