C++ 类型转换归纳

    本篇根据编程遇到的类型转换慢慢往上加东西。

 

    CString 转 int

 

CString str("123");//如果其中填的不全是数字,则返回从左到右碰到第一个非数字字符前的数字字符数值,如果最左边不是数字字符,返回0
int i= _ttoi(str);

 

    CString 转 char*(UNICODE字符集环境

 

#include <afxpriv.h>//添加必要的头文件

 

CString strTest = _T("abcd");//需转换的CString
USES_CONVERSION;
char *p = T2A(strTest);

 

    CString 转 CComVariant

 

CComVariant cobject;
CString result=L"HAHHAH";
cobject = result;

 

    CString 转 LPCSTR

 

#include<atlconv.h>//添加必要头文件
USES_CONVERSION;//在使用T2A前加上此句 
LPCSTR lPcstrName=(LPCSTR)T2A(cStringName);

 

    WCHAR 转 CHAR

DWORD dwNum = WideCharToMultiByte(CP_ACP, NULL, szPath, -1, NULL, 0, NULL, FALSE);
char  *chr = new char[dwNum];
if (!chr) 
{ 
	delete[]chr; 
}
WideCharToMultiByte(CP_ACP, 0, szPath, -1,chr, dwNum, NULL, NULL);

    WCHAR 转 string

string ws2s(const wstring& ws)//wchar_t转string
{
	size_t convertedChars = 0;
	string curLocale = setlocale(LC_ALL, NULL); //curLocale="C"
	setlocale(LC_ALL, "chs");
	const wchar_t* wcs = ws.c_str();
	size_t dByteNum = sizeof(wchar_t)*ws.size() + 1;
	//cout << "ws.size():" << ws.size() << endl;            //8  “123ABC你好”共8个字符

	char* dest = new char[dByteNum];
	wcstombs_s(&convertedChars, dest, dByteNum, wcs, _TRUNCATE);
	//cout << "ws2s_convertedChars:" << convertedChars << endl; //11 共使用了11个字节存储多字节字符串 包括结束符
	string result = dest;
	delete[] dest;
	setlocale(LC_ALL, curLocale.c_str());
	return result;
}

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 


 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值