天天看點

寬字元串和标準字元串的轉換

//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<nSize;i++)

        {

            pDst=pDst[i+1];

        }

    }

    wstring wcstr(pDst);

    delete []pDst;

    return wcstr;

//2

class auto_setlocate

   public:

       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<char*>(ret.c_str()), wsz, ret.length());

        return ret;

    std::string wstring2string(const std::wstring& wstr)

        std::string ret(wstr.length()*2, '/0');

        std::wcstombs(const_cast<char*>(ret.c_str()), wstr.c_str(), wstr.length());

    std::wstring string2wstring(const char* sz)

        std::wstring ret(strlen(sz), '/0');

        std::mbstowcs(const_cast<wchar_t*>(ret.c_str()), sz, ret.length());

    std::wstring string2wstring(const std::string& str)

    {    

        std::wstring ret(str.length(), '/0');

        std::mbstowcs(const_cast<wchar_t*>(ret.c_str()), str.c_str(), str.length());

繼續閱讀