分享

c++ string 和wstring 之间的互相转换函数

 9loong 2011-04-09
http://blog.sina.com.cn/s/blog_5cf500730100e57o.html

#include <string>
std::
string ws2s(const std::wstring& ws)
{
    std::
string curLocale = setlocale(LC_ALL, NULL);        // curLocale "C";
    setlocale(LC_ALL, "chs");
    
const wchar_t* _Source = ws.c_str();
    size_t _Dsize 
= 2 * ws.size() + 1;
    
char *_Dest = new char[_Dsize];
    memset(_Dest,
0,_Dsize);
    wcstombs(_Dest,_Source,_Dsize);
    std::
string result = _Dest;
    delete []_Dest;
    setlocale(LC_ALL, curLocale.c_str());
    
return result;
}

std::wstring s2ws(
const std::string& s)
{
    setlocale(LC_ALL, 
"chs"); 
    
const char* _Source = s.c_str();
    size_t _Dsize 
= s.size() + 1;
    wchar_t 
*_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 
0_Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result 
= _Dest;
    delete []_Dest;
    setlocale(LC_ALL, 
"C");
    
return result;
}


( # )


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多