c++中string和wstring相互转换
string转wstring代码
wstring StringToWString(const string &str)
{
int num = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, NULL, 0);
wchar_t *wide = new wchar_t[num];
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, wide, num);
wstring w_str(wide);
delete[] wide;
return w_str;
}
wstring转string代码
string WStringToString(const wstring &wstr)
{
string str;
int nLen = (int)wstr.length();
str.resize(nLen, ' ');
int nResult = WideCharToMultiByte(CP_ACP, 0, (LPCWSTR)wstr.c_str(), nLen, (LPSTR)str.c_str(), nLen, NULL, NULL);
if (nResult == 0)
{
return "";
}
return str;
}
utf8编码特殊处理
如果程序中有使用中文,并且编码为utf-8的话,可能会出现乱码,可以尝试使用下面的方法:
wstring StringToWString(const string& str)
{
setlocale(LC_ALL, "zh_CN");
const char* point_to_source = str.c_str();
size_t new_size = str.size() + 1;
wchar_t *point_to_destination = new wchar_t[new_size];
wmemset(point_to_destination, 0, new_size);
mbstowcs(point_to_destination, point_to_source, new_size);
wstring result = point_to_destination;
delete[]point_to_destination;
return result;
}