文章目录
前言
问题说明:
微软在VS2013中去掉了对MBCS的支持,默认都是UNICODE编码,导致宽字节与多字节不同字符编码的问题。
解决方案说明:
由于编程环境差异,运用方案可能不同,请尝试其他方案。
一、int -> CString
(1)Format()方案
int num = 100;
CString cstrNum;
cstrNum.Format(_T("%d"), num ); // 使用Unicode字符集
二、string -> CString :
(1)c_str()方案
std::string str = "abc";
CString cstr(str.c_str()); // 这里直接放在了初始化中
(2)CA2T()方案
vs2015中自带转换方法CA2T()
std::string str = "abc";
CString cstr = CA2T(b);
三、string -> LPCTSTR :
(1)MultiByteToWideChar()方案
如果是 UNICODE 字符,需要自己写一个转换函数:
std::wstring stringToWstring(const std::string & str)
{
int strLength = (int)str.length() + 1;
int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), strLength, 0, 0);
wchar_t* buf = new wchar_t[len];
MultiByteToWideChar(CP_ACP, 0, str.c_str(), slength, buf, len);
std::wstring wstr(buf);
delete[] buf;
return wstr;
}
调用处:
std::string str = "abc";
std::wstring wstr = stringToWstring(str);
LPCWSTR result = wstr.c_str();
如果不是 UNICODE 字符:
std::string str = "abc";
LPCWSTR result = str.c_str();
四、CString -> int
(1)atoi()或_ttoi()方案
ANSI 字符集下
// ANSI
CString cstrNum("100");
int num = atoi(cstrNum);
// 或者
int num = _ttoi(cstrNum);
_wtoi
UNICODE 字符集下
// UNICODE
CString cstrNum("100");
int num = atoi(CT2A(cstrNum.Getbuff()));
// 或者
int num = _ttoi(cstrNum);
五、CString -> string :
(1)CStringA()方案
CString可能是unicode编码(CString通过宏来确定到底是CStringA还是CStringW),因此应该都先将之转化为mbcs编码,也就是CStringA。
CString cstr = _T("abc");
std::string str = CStringA(cstr);
(2)CStringW()、CStringA()方案
vs2010 Unicode 可用:
CStringW strw(L"abc");
CStringA stra(strw.GetBuffer(0));
strw.ReleaseBuffer();
std::string str(stra.GetBuffer(0));
stra.ReleaseBuffer();
(3)T2A()方案
// 首先需要包含头文件 #include <atlconv.h>
// 在使用前,记得添加一行宏命令
USES_CONVERSION;
CString cstr = "abc";
string str = T2A(cstr.GetBuffer(0));
cstr.ReleaseBuffer();
(4)W2A()方案
// 首先需要包含头文件 #include <atlconv.h>
// 在使用前,记得添加一行宏命令
USES_CONVERSION;
CString cstr = _T("abc");
std::string str = W2A(cstr);
(5)CT2A()方案
CString cstr = "abc";
string str = CT2A(cstr);
(6)CT2CA()方案
CString cstr= _T("abc");
std::string = CT2CA(cstr.GetBuffer(0));