为什么不能转换TCHAR *为char *
-
21-09-2019 - |
题
错误C2664:'的strcpy:不能从 'TCHAR *' 转换参数1至 '字符*' 代码:
LPCTSTR name, DWORD value
strcpy (&this->valueName[0], name);
错误C2664: 'strlen的':不能从 'LPCTSTR' 转换参数1至 '为const char *'
LPCTSTR name;
strlen (name)
以上一类的代码在另一个项目中工作得很好,我找不到为什么它不在这个MS VS2010项目工作的原因。
解决方案
您需要使用的功能,例如 wcstombs 一>当_UNICODE被定义。要么或者只是使用 _tcslen (查看下<在TCHAR字符串,编译器将其传送到任何strlen的,或者如果你正在使用Unicode或不依赖wcslen EM>通用文本例程映射的)。
其他提示
大概是因为TCHAR被定义为在你的项目中的一个一个字符,而不是在VS2010之一,它可能为wchar_t的。
如果您的项目定义UNICODE / _UNICODE,这是相同的,指定这是一个统一建立在项目设置,TCHARS将wchar_t的。
您基本上需要决定是否使用Unicode或不是,如果你这样做,你需要改变经常调用等strncpy()函数的宽字符等效或使用T-变体能改变一样TCHARS做。看看帮助函数strncpy或其他功能,看看广域或T-变体叫什么。
您还可以看看MSDN的呼叫如的strcpy ,在那里你可以看到宽字符版本被称为wcscpy和T版本被称为_tcscpy。我建议你坚持使用T-版本,如果你要使用,要么使用Unicode或没有,或使哪一个你要使用,然后与坚持一个明智的决定不同的项目的代码。哪一个更好取决于你的情况,我会说,并可以调用一些“宗教”的观点......
您的项目是一个unicode项目?如果是的话,我相信TCHAR
将相当于一个wchar_t
而非char
使您的转换尝试无效。 看到这里获取更多信息。
下面是一些代码,会做的伎俩对你来说,它最初发布于www.wincli.com/?p=72但在这里我封装成一个小类:)
class char_args
{
private:
char **l_argn;
int arg_num;
int wstrlen(_TCHAR * wstr)
{
int l_idx = 0;
while (((char*)wstr)[l_idx] != 0) l_idx += 2;
return l_idx;
}
// Allocate char string and copy TCHAR->char->string
char *wstrdup(_TCHAR *wSrc)
{
int l_idx = 0;
int l_len = wstrlen(wSrc);
char *l_nstr = (char *)malloc(l_len);
if (l_nstr) {
do {
l_nstr[l_idx] = (char)wSrc[l_idx];
l_idx++;
} while ((char)wSrc[l_idx] != 0);
}
l_nstr[l_idx] = 0;
return l_nstr;
}
char_args & operator=(const char_args&); // does not allow assignment of class
char_args(const char_args&); // does not allow copy construction
public:
char_args(int argcc, _TCHAR* argv[]) : arg_num(argcc)
{
l_argn = (char **)malloc(argcc *sizeof(char*));
for (int idx = 0; idx < argcc; idx++) l_argn[idx] = wstrdup(argv[idx]);
}
~char_args()
{
for(int idx = 0; idx < arg_num; idx++) if (l_argn[idx]) free(l_argn[idx]);
free(l_argn);
}
const char * operator[](const int &i)
{
if (i < arg_num) return l_argn[i]; else return 0;
}
const int argc() { return arg_num; }
};
下面是使用的代码的一个示范:
int _tmain(int argc, _TCHAR* argv[])
{
char_args C_ARGV(argc, argv);
for(int i = 0; i < C_ARGV.argc(); i++) cout << C_ARGV[i] << endl;
}