C++宽窄字符串转换

转载:https://www.cnblogs.com/xuejianhui/p/3740243.html

 1 #include <string>
 2 
 3 std::string ws2s(const std::wstring& ws)
 4 {
 5     std::string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";
 6     setlocale(LC_ALL, "chs");
 7     const wchar_t* _Source = ws.c_str();
 8     size_t _Dsize = 2 * ws.size() + 1;
 9     char *_Dest = new char[_Dsize];
10     memset(_Dest,0,_Dsize);
11     wcstombs(_Dest,_Source,_Dsize);
12     std::string result = _Dest;
13     delete []_Dest;
14     setlocale(LC_ALL, curLocale.c_str());
15     return result;
16 }
17 
18 std::wstring s2ws(const std::string& s)
19 {
20     setlocale(LC_ALL, "chs"); 
21     const char* _Source = s.c_str();
22     size_t _Dsize = s.size() + 1;
23     wchar_t *_Dest = new wchar_t[_Dsize];
24     wmemset(_Dest, 0, _Dsize);
25     mbstowcs(_Dest,_Source,_Dsize);
26     std::wstring result = _Dest;
27     delete []_Dest;
28     setlocale(LC_ALL, "C");
29     return result;
30 }
31 
32 //c++ string 和wstring 之间的互相转换函数:
33 string a = "xxxx";
34 wstring b(a.begin(), a.end());

猜你喜欢

转载自www.cnblogs.com/Toya/p/11609938.html
今日推荐