在网上搜索到这个使用函数_tcscpy_s:
CString theString( "This is a test" );
int sizeOfString = (theString.GetLength() + 1);
LPTSTR lpsz = new TCHAR[ sizeOfString ];
_tcscpy_s(lpsz, sizeOfString, theString);
最后再转换一下lpsz为const型的
LPTSTR在UNICODE环境下编译考试,大提示是whca_t类型
但是DEBUG发现lpstr转换到const char*的时候,只截取了第一个字符,我是这样转换的
const char* xxx = (const char*)lpsz比如lpsz="player",那得到xxx="p"是不是我的转换那里有问题呢?
CString theString( "This is a test" );
int sizeOfString = (theString.GetLength() + 1);
LPTSTR lpsz = new TCHAR[ sizeOfString ];
_tcscpy_s(lpsz, sizeOfString, theString);
最后再转换一下lpsz为const型的
LPTSTR在UNICODE环境下编译考试,大提示是whca_t类型
但是DEBUG发现lpstr转换到const char*的时候,只截取了第一个字符,我是这样转换的
const char* xxx = (const char*)lpsz比如lpsz="player",那得到xxx="p"是不是我的转换那里有问题呢?
const char* xxx = (LPCTSTR)strCString;
T2A();
原因:由于使用的是Unicode没有字母前面都添加一个字节的0,因此"player",在内存中变成0x0070, 0x006c, 0x0061, 0x0079, 0x0065, 0x0072。由于是在x86平台上,硬盘上的顺序是0x7000, 0x6c00, 0x6100, 0x7900, 0x6500, 0x7200。所以你强制类型转换成一个字节的char,就按上面的顺序读取了字符。第一个字符是0x70,第二个是0x00....。输出的时候,第二个字符是0x00就是字符串的终止符,所以就输出了0x70,也就是p。
解决:
_tcscpy(lpsz, sizeOfString, theString.GetBuffer(0));
theString.ReleaseBuffer();
这样就行了。
应该用LPTSTR,或者TCHAR*
CStringA astr=(CStringA)ustr;
我的QQ群19206896
如果CString strCString = "asdfasdf"能通过,就说明不是UNI吧~
CString str(L"This is a test");
int len = WideCharToMultiByte( CP_ACP , 0 , str , str.GetLength() , NULL , 0 , NULL , NULL );
char* pAscii =new char[len+1];
len = WideCharToMultiByte( CP_ACP , 0 , str , str.GetLength() , pAscii , len +1 , NULL ,NULL );
pAscii[len] = 0; const char* xxx = (const char*)pAscii; char a = xxx[0];
char b = xxx[1];
char c = xxx[2];
char d = xxx[3];
测试正确。