方法一:MultiByteToWideChar、WideCharToMultiByte
BOOL StringToWString(const std::string &str,std::wstring &wstr)
{
int nLen = (int)str.length();
wstr.resize(nLen,L’ ‘);
int nResult = MultiByteToWideChar(CP_ACP,0,(LPCSTR)str.c_str(),nLen,(LPWSTR)wstr.c_str(),nLen);
if (nResult == 0)
{
return FALSE;
}
return TRUE;
}
//wstring高字节不为0,返回FALSE
BOOL WStringToString(const std::wstring &wstr,std::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 FALSE;
}
return TRUE;
}
方法二:std::copy
std::wstring StringToWString(const std::string &str)
{
std::wstring wstr(str.length(),L’ ‘);
std::copy(str.begin(), str.end(), wstr.begin());
return wstr;
}
8 //只拷贝低字节至string中
9 std::string WStringToString(const std::wstring &wstr)
10 {
11 std::string str(wstr.length(), ‘ ‘);
12 std::copy(wstr.begin(), wstr.end(), str.begin());
13 return str;
14 }