Recently, in C ++ programming, I often encounter the problem that the conversion between multi-byte characters and wide-byte characters is required. I have always pasted those codes on my own. I am in trouble, so I wrote a class to encapsulate the conversion between wchar_t and char Types. Others, such as CString \ LPWSTR \ TCHAR CHAR \ LPSTR, are also used in the same way.
Copy codeThe Code is as follows: # include <iostream>
Using namespace std;
Class CUser
{
Public:
CUser ();
Virtual ~ CUser ();
Char * WcharToChar (wchar_t * wc); // convert the width to the single byte
Wchar_t * CharToWchar (char * c); // convert a single byte to a wide byte
Void Release (); // Release resources
Private:
Char * m_char;
Wchar_t * m_wchar;
};
//////////////////////////////////////// //////////////////////////////////////// /////
/* Character type wchar_t char
/* Get the length of wcslen () strlen ()
/* Connect two strings wcscat () strcpy ()
/* Copy the string wcscpy () strcpy ()
/* Compare two strings wcscmp () strcmp ()
/* For specific parameters, see 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;
}
}
It is very easy to use:Copy codeThe Code is as follows: 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;