C++ programming the conversion of CString string and char arrays

  • 2020-05-30 20:55:14
  • OfStack

C++ programming the conversion of CString, string and char arrays

Although there are a lot of articles about the conversion of CString, string and char arrays on the Internet, it feels very messy and confusing, and many of them can't really achieve the purpose. Here, I post the conversion method I have debugged here and make a note.

Compile environment: vs2008, Use Unicode Character Set

//----------------ANSI String conversion to UNICODE string ----------------------//  
//  The array to be converted   
char szDCBparam[50] = {'0','1','\0'};  
//  Calculate the required buffer size   
DWORD dwNum = MultiByteToWideChar (CP_ACP, 0, szDCBparam, -1, NULL, 0);  
//  Allocate a buffer to hold the converted data   
wchar_t *pwText = new wchar_t[dwNum] ;  
//  The converted data is stored pwText The space it's pointing to  
if (!MultiByteToWideChar (CP_ACP, 0, szDCBparam, -1, pwText, dwNum))  
//  note :  If it is char Turn type array CString , direct use CString szTest = CString(szDCBparam);
//----------------UNICODE String conversion to ANSI string ----------------------// 
//---------------- will CString to char Type of the array ---------------------------// 
//  Data to be transformed   
CString szErrorInfo = _T("this is a test string!");  
//  Save the error message ANSI Buffer for strings , Note that the buffer should be large enough   
char InfoString[100];  
//  The converted data is stored InfoString In the array  
if (!WideCharToMultiByte(CP_ACP,0,LPCTSTR(szErrorInfo),-1,InfoString,100,NULL,NULL))  
//---------------- will CString to string----------------------// 
CString cstr=_T("test");  
std::string str = (CStringA)cstr;  
//  Pay attention to , in vs2008 Under the , use std::string temp = cstr.GetBuffer(0) I can't. 
//---------------- will string to CString----------------------// 
std::string strTest = "test"; 
CString cstrTest = CString(strTest.c_str()); 

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!

Related articles: