在以前VC++6.0中默认的字符集是多字节字符集(MBCS:Multi-Byte Character Set),而VS2005及以后默认的字符集是Unicode,这样导致以前在VC6.0中非常简单实用的各类字符操作和函数在VS2010环境下运行时会报各种各样的错误。
字符集可以通过工程属性修改:“工程-属性-字符集”。
CString在Unicode和多字节字符集下的区别:CString 是基于 TCHAR 数据类型的。如果为程序的生成定义了符号 _UNICODE,则会将 TCHAR 定义为 wchar_t 类型(一个 16 位的字符编码类型);否则,会将它定义为 char(普通的 8 位字符编码)。于是,在 Unicode 下,CString 由 16 位字符组成。如果没有 Unicode,它们则由 char 类型的字符组成(来自MSDN)。
以下是CString在Visual C++ .NET 2010环境中Unicode字符集下CString和char *之间相互转换的几种方法,其实也就是Unicode字符集与MBCS字符集转换。
1.Unicode下CString转换为char *
方法一: 使用API:WideCharToMultiByte进行转换
CString str = _T("你好,世界!Hello,World"); //注意:以下n和len的值大小不同,n是按字符计算的,len是按字节计算的 int n = str.GetLength(); //获取宽字节字符的大小,大小是按字节计算的 int len = WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),NULL,0,NULL,NULL); //为多字节字符数组申请空间,数组大小为按字节计算的宽字节字节大小 char * pFileName = new char[len+1]; //以字节为单位 //宽字节编码转换成多字节编码 WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),pFileName,len,NULL,NULL); pFileName[len+1] = ‘0‘; //多字节字符以’