宽字节与多字节之间的转换

string 与 wstring 相互间的转换

第一种方法

调用Windows的API函数WideCharToMultiByte()函数和MultiByteToWideChar()函数

第二种方法

使用ATL的CA2W类和W2CA类。或使用A2W宏与W2A宏。

第三种方法

跨平台的方法,使用CRT库的mbstowcs()函数和wcstombs()函数,需设置locale

string ws2s(const wstring str)
{
    size_t _DSize = 2*str.size()+1;
    char * _Dest = new char[_DSize];
    memset(_Dest, 0, _DSize);
    WideCharToMultiByte(CP_ACP, NULL, str.c_str(), str.size(), _Dest, _DSize, NULL, NULL);
    string result = _Dest;
    delete [] _Dest;
    return result;
}
string ws2s(const wstring str)
{
    size_t _DSize = 2*str.size()+1;
    char * _Dest = new char[_DSize];
    memset(_Dest, 0, _DSize);
    wcstombs(_Dest, str.c_str(), _DSize);
    string result = _Dest;
    delete [] _Dest;
    return result;
}

 

string ws2s(const wstring str)
{
 string curLocale = setlocale(LC_ALL, NULL);
 setlocale(LC_ALL, "chs");
 size_t _DSize = 2*str.size()+1;
 const wchar_t * _Source = str.c_str();
 char * _Dest = new char[_DSize];
 memset(_Dest, 0, _DSize);
 wcstombs(_Dest, _Source, _DSize);
 string result = _Dest;
 delete [] _Dest;
 setlocale(LC_ALL, curLocale.c_str());
 return result;
}

多字节转换为宽字节,原理相同,参照如上代码

转载于:https://www.cnblogs.com/kingdom_0/articles/2823671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值