C++

String manipulation in C++ an example of wide and narrow character conversion


String manipulation in C++ - an example of wide and narrow character conversion

MultiByteToWideChar

 int MultiByteToWideChar(
  _In_   UINT  CodePage,
  _In_   DWORD dwFlags,
  _In_   LPCSTR lpMultiByteStr,
  _In_   int  cbMultiByte,
  _Out_opt_ LPWSTR lpWideCharStr,
  _In_   int  cchWideChar
 );
  Parameter description:
  CodePage Commonly used: CP_ACP , CP_UTF8
  dwFlags : 0
  lpMultiByteStr [in] :
     Points to the string to be converted.
  cbMultiByte [in] :
    lpMultiByteStr " In bytes " The size of the.
     Set up the  0 , the function fails;
     Set up the  -1 , the function handles the entire string, including \0 String, resulting in a wide string with \0 The length returned is also included \0 The length of the;
     Set up the  >0 , depending on whether it is included \0 , the result returned will be adjusted accordingly.
  lpWideCharStr [out, optional] :
     Points to the buffer that receives the wide string.
  cchWideChar [in] :
    lpWideCharStr  Pointing buffer " Calculated in character size " The size of the.
     Set up the  0 To make  lpWideCharStr  Invalid and causes the function to return what is required " Calculated in character size " The size of the.

Code:

 int requiredBufSize = MultiByteToWideChar(CP_ACP, 0, src, -1, NULL, 0);
 if (requiredBufSize > 0)
 {
   WCHAR *pBuffer = new WCHAR[requiredBufSize];
   MultiByteToWideChar(CP_ACP, 0, src, -1, pBuffer, requiredBufSize);
 }

WideCharToMultiByte

 int WideCharToMultiByte(
  _In_   UINT  CodePage,
  _In_   DWORD  dwFlags,
  _In_   LPCWSTR lpWideCharStr,
  _In_   int   cchWideChar,
  _Out_opt_ LPSTR  lpMultiByteStr,
  _In_   int   cbMultiByte,
  _In_opt_ LPCSTR lpDefaultChar,
  _Out_opt_ LPBOOL lpUsedDefaultChar
 );
  Parameter description:
  lpDefaultChar [in, optional] : NULL
  lpUsedDefaultChar [out, optional] : NULL
   Other parameters reference  MultiByteToWideChar

Code:

 int requiredBufSize = WideCharToMultiByte(CP_ACP, 0, src, -1, NULL, 0, NULL, NULL);
 if (requiredBufSize > 0)
 {
   char *pBuffer = new char[requiredBufSize];
   WideCharToMultiByte(CP_ACP, 0, src, -1, pBuffer, requiredBufSize, NULL, NULL);
 }

If you have any questions, please leave a message or come to the site community to exchange discussion, thank you for reading, hope to help you, thank you for your support of the site!