CString转换

1.CString 和char * 相互转换

CString >char *


	//CString 转化成 char* 之一:强 制类型转换为 LPCTSTR;
	CString s;
	s="text";
	LPCTSTR str = s;
	m_label.SetWindowText(str);

char *> CString

//char* 转 CString
	CString str;
	const char* buf = "test is ok";
	str.Format(_T("%s"), buf);
	m_label.SetWindowText(str);

2.CString 和std::string 相互转换

CString > std::string

//头部加
//#include <string>
//using namespace std;
//CString 转 string
std::string buf;
CString str = _T("test");
buf = str.GetBuffer(str.GetLength());

std::string >CString

// string 转 CString
CString str;
std::string strStr = "test";
str = strStr.c_str();

3.CString 和 TChar* 相互转换

CString>TChar

CString str(_T("123"));
	int iLen = str.GetLength();
	TCHAR* szRs = new TCHAR[iLen];
	lstrcpy(szRs, str.GetBuffer(iLen));
	str.ReleaseBuffer();

TChar>CString

TCHAR szTchar[18] = L"TCHAR";  
 CString  str;  
 str.Format(_T("%s"),szTchar);  

4.CString 数字字符和int,double的抓换

CString>int、double

CString str1(_T("123"));
int num = _ttoi(str1);

int、double >CString

int num = 6;
CString str;
str.Format(_T("%d"), num);

5.CString 和 WChar* 相互转换

CString>WChar*


WideCharToMultiByte

函数功能:该函数映射一个unicode字符串到一个多字节字符串。

wchar_t sBuf[] = L"中国伟大复兴梦";

	//获取转换所需的目标缓存大小
	DWORD dBufSize = WideCharToMultiByte(CP_OEMCP, 0, sBuf, -1, NULL, 0, NULL, FALSE);
	
	//分配目标缓存
	char* dBuf = new char[dBufSize];
	memset(dBuf, 0, dBufSize);
	
	//转换
	int nRet = WideCharToMultiByte(CP_OEMCP, 0, sBuf, -1, dBuf, dBufSize, NULL, FALSE);
	
	if (nRet <= 0)
	{
		printf("转换失败\n");
	}
	else
	{
		printf("转换成功\nAfter Convert: %s\n", dBuf);
	}
	delete[]dBuf;

w2a宏

CString >char *

	//头文件#include "atlconv.h"
	USES_CONVERSION;
	CString tmpStr;
	WCH LineChar="fdsfdsa";
	const char* cLineChar = A2W(LineChar);

getbuffer的使用

GetBuffer()主要作用是将字符串的缓冲区长度锁定
GetBuffer()主要作用是将字符串的缓冲区长度锁定,releaseBuffer则是解除锁定,使得CString对象在以后的代码中继续可以实现长度自适应增长的功能。

#include <string>
using namespace std;
std::string str;
CString cstr;
str = cstr.GetBuffer(0);
cstr.ReleaseBuffer();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值