C++ string和wstring互转实现

  [转载] http://www.cppblog.com/kenwell/archive/2008/05/21/50661.html  很好,很强大,用到就是赚到!

  代码如下:

 1 #include <string>
 2 std::string ws2s(const std::wstring& ws)
 3 {
 4     std::string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";
 5     setlocale(LC_ALL, "chs");
 6     const wchar_t* _Source = ws.c_str();
 7     size_t _Dsize = 2 * ws.size() + 1;
 8     char *_Dest = new char[_Dsize];
 9     memset(_Dest,0,_Dsize);
10     wcstombs(_Dest,_Source,_Dsize);
11     std::string result = _Dest;
12     delete []_Dest;
13     setlocale(LC_ALL, curLocale.c_str());
14     return result;
15 }
16 
17 std::wstring s2ws(const std::string& s)
18 {
19     setlocale(LC_ALL, "chs"); 
20     const char* _Source = s.c_str();
21     size_t _Dsize = s.size() + 1;
22     wchar_t *_Dest = new wchar_t[_Dsize];
23     wmemset(_Dest, 0, _Dsize);
24     mbstowcs(_Dest,_Source,_Dsize);
25     std::wstring result = _Dest;
26     delete []_Dest;
27     setlocale(LC_ALL, "C");
28     return result;
29 }

  

原文地址:https://www.cnblogs.com/MakeView660/p/6046622.html