std::wstring StringToWString(const std::string &str)
{
std::wstring wstr(str.length(),L‘ ‘);
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}
//只拷贝低字节至string中
std::string WStringToString(const std::wstring &wstr)
{
std::string str(wstr.length(), ‘ ‘);
std::copy(wstr.begin(), wstr.end(), str.begin());
return str;
}
上面的对于英文字符串 是正确的,对于中文是错误的,下面的代码则适用于中英文!
std::string AVentilationGraph::wstring2string(const std::wstring &wstr) { std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C"; setlocale(LC_ALL, "chs"); const wchar_t* _Source = wstr.c_str(); size_t _Dsize = 2 * wstr.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; } //wstring 转 string std::wstring AVentilationGraph::string2wstring(const std::string &str) { setlocale(LC_ALL, "chs"); const char* _Source = str.c_str(); size_t _Dsize = str.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; }
时间: 2024-10-08 19:55:01