1、wstring string转换
1)win32下wchar_t占2个字节,linux下wchar_t占4个字节。wchar_t的高字节应该存放在char数组的低字节。
2)win下面有函数WideCharToMultiByte() 和 MultiByteToWideChar()
3)linux类似的函数有:mbstowcs() wcstombs()
wcstombs和mbstowcs使用:
#include <locale.h>
setlocale(LC_ALL, "");
wcstombs(char * to,wchar_t * from,size_t _maxCount);
mbstowcs(wchar_t * to,char * from,size_t _maxCount); //_maxCount,大小一定要是from长度的2倍,否则出来的中文也会是乱码
demo:
#include <string>
#include <stdlib.h>
#include <locale.h>
std::string ws2s(const std::wstring& ws)
{
std::string curLocale = setlocale(LC_ALL, NULL); // curLocale = "C";
setlocale(LC_ALL, "chs");
const wchar_t* _Source = ws.c_str();
size_t _Dsize = 2 * ws.size() + 1;
char *_Dest = new char[_Dsize];
memset(_Dest,0,_Dsize);
wcstombs(_Dest,_Source,_Dsize);
std::string result = _Dest;
delete []_Dest;
setlocale(LC_ALL, curLocale.c_str());
return result;
}
std::wstring s2ws(const std::string& s)
{
setlocale(LC_ALL, "chs");
const char* _Source = s.c_str();
size_t _Dsize = s.size() + 1;
wchar_t *_Dest = new wchar_t[_Dsize];
wmemset(_Dest, 0, _Dsize);
mbstowcs(_Dest,_Source,_Dsize);
std::wstring result = _Dest;
delete []_Dest;
setlocale(LC_ALL, "C");
return result;
}
2、Notice:
使用iostream中的io流输入输出wstring或者wchar时,设置locale后,使用wcin及wcout输入输出。
参考:
http://www.cnblogs.com/MichaelOwen/articles/2128771.html
http://www.ibm.com/developerworks/cn/linux/l-cn-ccppglb/index.html?ca=drs-