最近在C++編程中經常遇到需要多字節字符與寬字節字符相互轉換的問題,一直自己貼那幾句代碼。覺得麻煩,於是就自己寫了一個類來封裝wchar_t與char類型間的轉換,
其他的,諸如:CString\ LPWSTR\TCHAR CHAR\LPSTR之間也是一樣用
- #include <iostream>
- using namespace std;
- class CUser
- {
- public:
- CUser();
- virtual~ CUser();
- char* WcharToChar(wchar_t* wc);//寬字節轉單字節
- wchar_t* CharToWchar(char* c); //單字節轉寬字節
- void Release();//釋放資源
- private:
- char* m_char;
- wchar_t* m_wchar;
- };
- /////////////////////////////////////////////////////////////////////////////////////
- /*字符類型 wchar_t char
- /*獲取字符長度 wcslen() strlen()
- /*連接兩個字符串 wcscat() strcpy()
- /*復制字符串 wcscpy() strcpy()
- /*比較兩個字符串 wcscmp() strcmp()
- /*具體參數詳見www.linuxidc.com*/
- ////////////////////////////////////////////////////////////////////////////////////
- CUser::CUser()
- :m_char(NULL)
- ,m_wchar(NULL)
- {
- }
- CUser::~CUser()
- {
- Release();
- }
- char* CUser::WcharToChar(wchar_t* wc)
- {
- Release();
- int len= WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),NULL,0,NULL,NULL);
- m_char=new char[len+1];
- WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),m_char,len,NULL,NULL);
- m_char[len]='\0';
- return m_char;
- }
- wchar_t* CUser::CharToWchar(char* c)
- {
- Release();
- int len = MultiByteToWideChar(CP_ACP,0,c,strlen(c),NULL,0);
- m_wchar=new wchar_t[len+1];
- MultiByteToWideChar(CP_ACP,0,c,strlen(c),m_wchar,len);
- m_wchar[len]='\0';
- return m_wchar;
- }
- void CUser::Release()
- {
- if(m_char)
- {
- delete m_char;
- m_char=NULL;
- }
- if(m_wchar)
- {
- delete m_wchar;
- m_wchar=NULL;
- }
- }
使用的時候非常簡單了:
- WCHAR* wc=findData.cFileName;
- CUser u;
- char* c=u.WcharToChar(wc);
- cout<<c<<endl;
- CUser u;
- char* pBuffer=u.WcharToChar(szFullPath);
- cout<<totalNum<<" "<<pBuffer<<endl;