string与wstring的相互转换

来源:互联网 发布:jquery 双向数据绑定 编辑:程序博客网 时间:2024/06/05 23:39

在VS下编程经常涉及到Unicode编码,但一些旧的C++代码使用的字符串是string类型,不能对Unicode字符串进行存储。在开发WIN32程序时,若为了避免使用MFC,可以使用wstring作为字符串的存储结构,这时就需要string与wstring之间的转换。下面是我常用的两个函数。

wstring string_to_wstring(const string& str){int nLen = MultiByteToWideChar( CP_ACP, 0, str.c_str(), -1, NULL, NULL );LPWSTR lpwszStr = new wchar_t[nLen];MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, lpwszStr, nLen);wstring wszStr = lpwszStr;delete [] lpwszStr;return wszStr;}
string wstring_to_string(const wstring& wStr){int nLen = WideCharToMultiByte(CP_ACP, 0, wStr.c_str(), -1, NULL, 0, NULL, NULL);LPSTR lpszStr = new char[nLen];WideCharToMultiByte(CP_ACP, 0, wStr.c_str(), -1, lpszStr, nLen, NULL, NULL);string szStr = lpszStr;delete [] lpszStr;return szStr;}