MFC实用技巧之CString,char *,string互转

目录

CString转char *

char *转CString

string转char *

char *转string

CString转string

string转CString


在mfc中,char* ,CString,string之间的转换是使用非常频繁的,这里参考了网上的许多方法,这里做一个总结

CString转char *

void CString_to_chars()
{
	char ch[256];
	CString cs = _T("this is test CString_to_chars");
	
#ifndef  UNICODE
	int str_len = cs.GetLength();
	char *buf = cs.GetBuffer(str_len);
	memcpy(ch, buf, str_len);
	ch[str_len] = '\0';
	cs.ReleaseBuffer();
#else
	int len = WideCharToMultiByte(CP_ACP, 0, cs, -1, NULL, 0, NULL, NULL);//m_csFileName.GetLength()	
	WideCharToMultiByte(CP_ACP, 0, cs, -1, ch, len, NULL, NULL);
	ch[len + 1] = '\0';
#endif
	printf("%s\n", ch);
}

char *转CString

void chars_to_CString()
{
	CString cs;
	const char *ch = "this is test chars_to_CString";
	const char ch2[] = "this is test chars_to_CString";

	cs = ch;
	//cs = ch2;
	//cWnd->SetDlgItemText(IDC_EDIT_CSTRING_OUTPUT, cs);
}

string转char *

void string_to_chars()
{
	string ss = "this is test string_to_chars";
	char ch[256];
	memcpy(ch, ss.c_str(), ss.length() + 1);
	printf("%s\n", ch);
}

char *转string

void chars_to_string()
{
	string ss;
	const char *ch = "this is test chars_to_string";
	const char ch2[] = "this is test chars_to_string";
	ss = ch;
	//ss = ch2;
	cout << ss << endl;
}

CString转string

void CString_to_string()
{
	string ss;
	CString cs = _T("this is test CString_to_string");
	
#if 1	//方法一
	ss = CT2A(cs.GetString());
#else	//方法二
	#ifndef  UNICODE
		ss = CA2A(cs.GetString());
	#else
		ss = CW2A(cs.GetString());
	#endif
#endif
	cout << ss << endl;
}

string转CString

void string_to_CString()
{
	string ss = "this is test string_to_CString";
	CString cs;
#if 1	//方法一
	cs = CA2T(ss.c_str());
#else	//方法二
	#ifndef  UNICODE
		cs = CA2A(ss.c_str());
	#else
		cs = CA2W(ss.c_str());
	#endif
#endif
        //cWnd->SetDlgItemText(IDC_EDIT_CSTRING_OUTPUT, cs);
}

其他的还有char转int,string转int等等,相关资料包括demo代码请到我<MFC实用技巧>篇最下的网盘链接中下载!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

在云巅

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

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

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

打赏作者

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

抵扣说明:

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

余额充值