C++中各种string 的相互转化 一 C++ 中 string 与 wstring 互转 方法一: string WideToMutilByte(const wstring& _src) { int nBufSize = WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, NULL, 0, 0, FALSE); char *szBuf = new char[nBufSize]; WideCharToMultiByte(GetACP(), 0, _src.c_str(),-1, szBuf, nBufSize, 0, FALSE); string strRet(szBuf); delete []szBuf; szBuf = NULL; return strRet; } wstring MutilByteToWide(const string& _src) { //计算字符串 string 转成 wchar_t 之后占用的内存字节数 int nBufSize = MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,NULL,0); //为 wsbuf 分配内存 BufSize 个字节 wchar_t *wsBuf = new wchar_t[nBufSize]; //转化为 unicode 的 WideString MultiByteToWideChar(GetACP(),0,_src.c_str(),-1,wsBuf,nBufSize); wstring wstrRet(wsBuf); delete []wsBuf; wsBuf = NULL; return wstrRet; } 转载:csdn 这篇文章里,我将给出几种C++ std::string 和std::wstring 相互转换的转换方法。 第一种方法:调用 WideCharToMultiByte()和MultiByteToWideChar(),代码如下(关于详细的解释,可以参考《windows 核心编程》): #include #include using namespace std; //Converting a WChar string to a Ansi string std::string WChar2Ansi(LPCWST R pwszSrc) { int nLen = WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, NULL, 0, NULL, NULL); if (nLen<= 0) return std::string(""); char* pszDst = new char[nLen]; if (NULL == pszDst) return std::string(""); WideCharToMultiByte(CP_ACP, 0, pwszSrc, -1, pszDst, nLen, NULL, NULL); pszDst[nLen -1] = 0; std::string strTemp(pszDst); delete [] pszDst; return strTemp; } string ws2s(wstring& inputws) { return WChar2Ansi(inputws.c_str()); } //Converting a Ansi string to WChar string std::wstring Ansi2WChar(LPCSTR pszSrc, int nLen) { int nSize = MultiByteToWideChar(CP_ACP, 0, (LPCSTR)pszSrc, nLen, 0, 0); if(nSize <= 0) return NULL; WCHAR *pwszDst = new WCHAR[nSize+1];...