CString轉字符數組時,數組中每個字符後面都會多出一個\0 的原因:
是Unicode字符集的問題。選擇項目->項目屬 性(或直接按alt+F7)->配置屬性,在右邊找到“字符集”,將“使用Unicode字符集”改爲“使用多字節字符集”。保存之後需要重新生成 解決方案,然後通過網上介紹的多種方法從CString轉字符數組每個字符後面再也不會多出\0字符了。
實際應用中轉換如下:
方法一:
char *p;
CString str="hello";
p=str.GetBuffer(str.GetLength());
str.ReleaseBuffer();
方法二:
CString str="hello";
char ch[20];
memcpy(ch,str,str.GetLength());
方法三:
char *ch;
CString str="hello";
ch=(LPSTR)(LPCTSTR)str;
在方法二中,最好不要使用memcpy,直接用strcpy_s(char*, CString)就可以了,因爲用memcpy也會出現亂碼尾巴。
如果不想改變Unicode字符集,網上也有介紹方法,但我沒有試過,在此列出來供網友們參考:
CString strPath = L"adfafs主聲音文件fsfsa";int nLength = strPath.GetLength();
int nBytes = WideCharToMultiByte(CP_ACP,0,strPath,nLength,NULL,0,NULL,NULL);
char* VoicePath = new char[ nBytes + 1];
memset(VoicePath,0,nLength + 1);
WideCharToMultiByte(CP_OEMCP, 0, strPath, nLength, VoicePath, nBytes, NULL, NULL);
VoicePath[nBytes] = 0;
delete [] VoicePath;
VoicePath = NULL;