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

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;
}

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

posted @ 2012-12-18 17:42  Kingdom_0  阅读(817)  评论(0编辑  收藏  举报