MFC 类型互转方案整理


前言

问题说明:

微软在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));
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Whitemeen太白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值