- UID
- 1029342
- 性别
- 男
|
最近在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; |
|