之前在网上找了,都是用调用WinAPI的 MultiByteToWideChar或是ATL的_BSTR过度。代码冗长,而且只适合在Windows平台。发现其实有个最简单的办法,利用BOOST库,兼顾平台无关与代码量。
#include <boost/locale.hpp>
#include <iostream>
int main(int argc, char** argv)
{
using namespace std;
wstring wtmp1 = L"我转换成了string";
string tmp1 = "我转换成了wstring";
wstring wtmp2 = boost::locale::conv::to_utf<wchar_t>(tmp1, "GBK");
string tmp2 = boost::locale::conv::from_utf<wchar_t>(wtmp1, "GBK");
setlocale(LC_ALL, "chs");
wcout << "Wide string:" << wtmp2 << endl;
cout << "MultiByte string:" << tmp2 << endl;
cin.get();
return 0;
}
Wide string:我转换成了wstring
MultiByte string:我转换成了string