VC++中 wstring和string的互相转换实现

在VC++开发中,经常会用到string和wstring,这就需要二者之间的转换,项目中封装了wstring和string相互转换的2个函数,实现如下:

//将wstring转换成string
std::string ConvertWStringToAnsi(std::wstring wstr)
{
	std::string result;
	int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
	if( len <= 0 )
		return result;

	char* buffer = new char[len + 1];
	if(buffer == NULL )
		return result;

	WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
	buffer[len] = '\0';               //字符串断尾
	result.append(buffer);            //赋值
	delete[] buffer;                  //删除缓冲区

	//返回值
	return result;
}


//将string转换成wstring
std::wstring ConvertAnsiToWString(std::string str)
{
	std::wstring result;

	int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);
	if( len < 0 )
		return result;

	wchar_t* buffer = new wchar_t[len + 1];
	if( buffer == NULL )
		return result;

	MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);

	buffer[len] = '\0';                    //字符串断尾
	result.append(buffer);                 //赋值
	delete[] buffer;                       //删除缓冲区

	//返回值
	return result;
}

  

转载于:https://www.cnblogs.com/JczmDeveloper/p/3527189.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值