宽字符串和标准字符串的转换
- 格式:doc
- 大小:51.50 KB
- 文档页数:2
宽字符串和标准字符串的转换
1 宽字符串和标准字符串的转换
string WstringToString(wstring str)
{
const wchar_t *pwc=str.c_str();
int
nLen=WideCharToMultiByte(CP_ACP,0,(LPCWSTR)pwc,-1,NULL,0,NULL,NULL);
if(nLen<=0) return string("");
char *presult=new char[nLen];
if (NULL==presult) return string("");
WideCharToMultiByte(CP_ACP,0,(LPCWSTR)pwc,-1,presult,nLen,NULL,NULL);
presult[nLen-1]=0;
string result(presult);
delete[] presult;
return result;
}
wstring StringToWstring(string str)
{
const char *pstr=str.c_str();
int nLen=str.size();
int nSize=MultiByteToWideChar(CP_ACP,0,(LPCSTR)pstr,nLen,0,0);
if (nSize<=0) return NULL;
WCHAR *pDst=new WCHAR[nSize+1];
if (pDst==NULL)return NULL;
MultiByteToWideChar(CP_ACP,0,(LPCSTR)pstr,nLen,pDst,nSize);
pDst[nSize]=0;
if (pDst[0]==0xFEFF)
{
for (int i=0;i { pDst[i]=pDst[i+1]; } } wstring wcstr(pDst); delete []pDst; return wcstr; } //下面是一位朋友写的,被我剽窃了 class auto_setlocate { public: 宽字符串和标准字符串的转换 2 auto_setlocate() { setlocale(LC_ALL, ""); } }; std::string wstring2string(const wchar_t* wsz) { static auto_setlocate as; std::string ret(wcslen(wsz)*2, '\0'); std::wcstombs(const_cast return ret; } std::string wstring2string(const std::wstring& wstr) { static auto_setlocate as; std::string ret(wstr.length()*2, '\0'); std::wcstombs(const_cast return ret; } std::wstring string2wstring(const char* sz) { static auto_setlocate as; std::wstring ret(strlen(sz), '\0'); std::mbstowcs(const_cast return ret; } std::wstring string2wstring(const std::string& str) { static auto_setlocate as; std::wstring ret(str.length(), '\0'); std::mbstowcs(const_cast return ret; }