一杯清酒邀明月
天下本无事,庸人扰之而烦耳。

1、std::wstring 转 std::string

 1 string WstringToString(const std::wstring wstr)
 2 {
 3 #if 1
 4     std::string result;
 5     int len = WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), NULL, 0, NULL, NULL);
 6     if( len <= 0 )
 7         return result;
 8  
 9     char* buffer = new char[len + 1];
10     if(buffer == NULL )
11         return result;
12  
13     WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), wstr.size(), buffer, len, NULL, NULL);
14     buffer[len] = '\0';
15     result.append(buffer);
16     delete[] buffer;
17  
18     return result;
19 #else
20     //unsigned len = (unsigned)str.size() * 4;
21     setlocale(LC_CTYPE, "");
22     //char *p = new char[len];
23     //wcstombs(p,str.c_str(),len);
24     //std::string str1(p);
25     //delete[] p;
26     //return str1;
27 #endif
28 }

2、std::string 转 std::wstring

 1 wstring StringToWString(const string str) 
 2 {
 3     //int num = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
 4     //wchar_t *wide = new wchar_t[num];
 5     //MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, num);
 6     //std::wstring w_str(wide);
 7     //delete[] wide;
 8     //return w_str;
 9  
10     wstring result;  
11     //获取缓冲区大小,并申请空间,缓冲区大小按字符计算  
12     int len = MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), NULL, 0);  
13     TCHAR* buffer = new TCHAR[len + 1];  
14     //多字节编码转换成宽字节编码  
15     MultiByteToWideChar(CP_ACP, 0, str.c_str(), str.size(), buffer, len);  
16     buffer[len] = '\0';             //添加字符串结尾  
17     //删除缓冲区并返回值  
18     result.append(buffer);  
19     delete[] buffer;  
20     return result;
21  
22 }

 

posted on 2021-08-13 11:34  一杯清酒邀明月  阅读(559)  评论(0编辑  收藏  举报