string与wstring相互转换

#简介

C++中字符串类的模板原型都是basic_string,string是普通的多字节版本(基于char),而wstring是Unicode版本(基于wchar_t)。

windows 默认unicode为utf16

typedef basic_string<char, char_traits<char>, allocator<char> >  string;
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >  wstring;

#转换

在一些情况下,需要用到string和wstring之间的转换,可以用下面的代码

inline std::string WtoA(const std::wstring &input)
{
	std::string dest_str;

	int utf8_count =
         ::WideCharToMultiByte(CP_ACP, 0, input.c_str(), (int)input.length(), NULL, 0, NULL, NULL);
        //如果第4个参数为-1,则返回值中包含'\0'
	if (utf8_count <= 0)
		return dest_str;

	dest_str.resize(utf8_count);

	if (!::WideCharToMultiByte(CP_ACP, 0, input.c_str(), (int)input.length(), &dest_str[0], utf8_count, NULL, NULL))
	{
		//转换失败
		dest_str.clear();
	}
	
	return dest_str;
}

inline std::wstring AtoW(const std::string &input)
{
	std::wstring dest_str;

	int unicode_count = 
        ::MultiByteToWideChar(CP_ACP, 0, input.c_str(), (int)input.length(), NULL, 0);
        //如果第4个参数为-1,则返回值中包含'\0'
	if (unicode_count <= 0)
		return dest_str;

	dest_str.resize(unicode_count);
		
	if (!::MultiByteToWideChar(CP_ACP, 0, input.c_str(), (int)input.length(), &dest_str[0], unicode_count))
	{
		//转换失败
		dest_str.clear();
	}
	return dest_str;
}

#参考 1.http://msdn.microsoft.com/en-us/library/windows/desktop/dd374081(v=vs.85).aspx

转载于:https://my.oschina.net/u/1581994/blog/270367

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值