_tcslen in Multibyte character set: how to convert WCHAR [1] to const char *?
I search over internet for about 2 hours and I don't find any work solution.
My program have m开发者_如何学运维ultibyte character set, in code i got:
WCHAR value[1];
_tcslen(value);
And in compiling, I got error:
'strlen' : cannot convert parameter 1 from 'WCHAR [1]' to 'const char *'
How to convert this WCHAR[1] to const char * ?
I assume the not-very-useful 1-length WCHAR
array is just an example...
_tcslen
isn't a function; it's a macro that expands to strlen
or wcslen
according to the _UNICODE
define. If you're using the multibyte character set (which means _UNICODE
ISN'T defined) and you have a WCHAR
array, you'll have to use wcslen
explicitly.
(Unless you're using TCHAR
specifically, you probably want to avoid the _t functions. There's a not-very-good overview in MSDN at http://msdn.microsoft.com/en-us/library/szdfzttz(VS.80).aspx; does anybody know of anything better?)
Try setting "use unicode" in your projects settings in VS if you want _tcslen
to be wcslen
, set it to "use multibyte" for _tcslen
to be strlen
. As some already pointed out, _t
prefixed functions (as many others actually, e.g. MessageBox()
) are macros that are "expanded" based on the _UNICODE
precompiler define value.
Another option would be to use TCHAR
instead of WCHAR
in your code. Although I'd say a better idea would be to just stick to either wchar_t
or char
types and use appropriate functions with them.
And last but not least, as the question is tagged c++, consider using std::string
(or std::wstring
for that matter) and std::vector
instead of char buffers. Using those with C API functions is trivial and generally a lot safer.
use conversion function WideCharToMutliByte() .
http://msdn.microsoft.com/en-us/library/dd374130(VS.85).aspx
_tcslen takes WCHAR pointers or arrays as input only when UNICODE is #defined in your enviroment.
From the error message, I'd say that it isn't
The best way to define unicode is to pass it as a parameter to the compiler. For Microsoft C, you would use the /D switch
cl -c /DUNICODE myfile.cpp
or you could change your array declaration to TCHAR, which like _tcslen will be char when UNICODE is not #defined and WCHAR when it is.
精彩评论