The conversion of C++ wide characters and normal characters

  • 2020-05-24 05:57:01
  • OfStack

The conversion of C++ wide characters to normal characters

Convert the string to a wide string,

Example code:


wstring string2Wstring(string sToMatch) 
{   
#ifdef _A_WIN 
  int iWLen = MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), 0, 0 ); //  Calculates the length of the converted wide string. (does not contain end of string)  
  wchar_t *lpwsz = new wchar_t [iWLen + 1]; 
  MultiByteToWideChar( CP_ACP, 0, sToMatch.c_str(), sToMatch.size(), lpwsz, iWLen ); //  Formal conversion.  
  lpwsz[iWLen] = L'/0';  
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#elif _A_LINUX 
  setlocale( LC_CTYPE, "" ); //  Very important. No 1 The conversion will fail.  
  int iWLen = mbstowcs( NULL, sToMatch.c_str(), sToMatch.length() ); //  Calculates the length of the converted wide string. (does not contain end of string)  
  wchar_t *lpwsz = new wchar_t[iWLen + 1]; 
  int i = mbstowcs( lpwsz, sToMatch.c_str(), sToMatch.length() ); //  Conversion. (the converted string has an end character)  
  wstring wsToMatch(lpwsz); 
  delete []lpwsz; 
#endif 
  return wsToMatch; 
} 
// Convert a wide string to a string and use the output  
string wstring2string(wstring sToMatch) 
{   
#ifdef _A_WIN 
  string sResult; 
  int iLen = WideCharToMultiByte( CP_ACP, NULL, sToMatch.c_str(), -1, NULL, 0, NULL, FALSE ); //  Calculates the length of the converted string. (contains end of string)  
  char *lpsz = new char[iLen]; 
  WideCharToMultiByte( CP_OEMCP, NULL, sToMatch.c_str(), -1, lpsz, iLen, NULL, FALSE); //  Formal conversion.  
  sResult.assign( lpsz, iLen - 1 ); //  right string Object for assignment.  
  delete []lpsz; 
#elif _A_LINUX 
  int iLen = wcstombs( NULL, sToMatch.c_str(), 0 ); //  Calculates the length of the converted string. (does not contain end of string)  
  char *lpsz = new char[iLen + 1]; 
  int i = wcstombs( lpsz, sToMatch.c_str(), iLen ); //  Conversion. (no end)  
  lpsz[iLen] = '/0'; 
  string sResult(lpsz); 
  delete []lpsz; 
#endif 
  return sResult; 
} 

Thank you for reading, I hope to help you, thank you for your support of this site!


Related articles: