Multi-byte string and wide String Conversion
To convert a multi-byte string to a wide string, use the c api Win32 API.
C API: mbstowcs, wcstombs
Win32 API: multibytetowidechar, widechartomultibyte
The following describes how to use Win32 API. For more information about c api usage, see Win32 API.
First, widechartomultibyte
You usually need to configure four parameters (if other parameters are used ),RedMarked part.
It is the Source width string, the length to be converted (-1, the entire string), the target multi-byte string, and the target buffer length.
The return value indicates the actual length (including the terminator) required for conversion to the target multi-byte string ).
Therefore, widechartomultibyte is usually called twice: the first generation of the Target Buffer length, the second generation of the target string, as shown below
Wchar_t * WCS = l "China, hello! I love you! ";
Int lengthofmbs = widechartomultibyte (cp_acp, 0,WCS,-1, null, 0, Null, null );
Char * MBS = new char [lengthofmbs];
Widechartomultibyte (cp_acp, 0,WCS,-1, MBS, lengthofmbs, Null, null );
Delete MBS;
MBS = NULL;
The usage of multibytetowidechar is similar to that
Char * MBS = "China, hello! I love you! ";
Int lengthofwcs = multibytetowidechar (cp_acp, 0,MBS,-1, null, 0);
Wchar_t * WCS = new wchar_t [lengthofwcs];
Multibytetowidechar (cp_acp, 0,MBS,-1, WCS, lengthofwcs);
Delete WCS;
WCS = NULL;
The following two functions encapsulate the conversion process.
# Include <windows. h>
# Include <string>
STD: String wcstombs (const STD: wstring & WCS ){
Int lengthofmbs = widechartomultibyte (cp_acp, 0, WCS. c_str (),-1, null, 0, null, null );
Char * MBS = new char [lengthofmbs];
Widechartomultibyte (cp_acp, 0, WCS. c_str (),-1, MBS, lengthofmbs, null, null );
STD: String result = MBS;
Delete MBS;
MBS = NULL;
Return result;
}
STD: wstring mbstowcs (const STD: string & MBS) {
int lengthofwcs = multibytetowidechar (cp_acp, 0, MBS. c_str (),-1, null, 0);
wchar_t * WCS = new wchar_t [lengthofwcs];
multibytetowidechar (cp_acp, 0, MBS. c_str (),-1, WCS, lengthofwcs);
STD: wstring result = WCS;
Delete WCS;
WCS = NULL;
return result;
}