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-