在vc6中喜欢用CString,因为它用起来方便,可以容易地进行字符串赋值,复制,格式化,甚至相加,然而到了vc8中,这些操作似乎都不能用了。连CString str = "Hello World!";都会报错。
网上找了一下,原来是vc8下的应用程序默认支持unicode,采用的是宽字符集,因此一般的字符串需要加一些操作才能兼容了。CString内部即是采用wchar*来表示字符串的。如果是新建一个程序,当然可以全部用wchar,这样你的程序支持度更好。但是需要更新以前的程序时,可能就要面对char和wchar的转换了。
下面转的关于wchar与char的转换比较有用:
1.头文件中要定义宏;
#define UNICODE
#define _UNICODE
2.char转换成wchar
const char *pFilePathName = "c:\\aa.dll";
int nLen = strlen(pFilePathName) + 1;
int nwLen = MultiByteToWideChar(CP_ACP, 0, pFilePathName, nLen, NULL, 0);
TCHAR lpszFile[256];
MultiByteToWideChar(CP_ACP, 0, pFilePathName, nLen, lpszFile, nwLen);
3.wchar转换成char
char *pFilePathName;
TCHAR lpszFile[256];
_tcscpy(lpszFile, _T("c:\\aa.dll"));
int nLen = wcslen(wstr)+1;
WideCharToMultiByte(CP_ACP, 0, lpszFile, nLen, pFilePathName, 2*nLen, NULL, NULL);
另外补充一些vc8下关于wchar的常用操作:
赋字符串常量:CString str=_T("Hello World!");
字符串格式化:wsprintf(str1, "%s", str2); str1.Format(_T("%s"), str2);
字符串拷贝:wcscpy(str_dst, str_src);或wsprintf(str_dst, str_stc);
求字符串长度:int len = wcslen(str);