SoFunction
Updated on 2024-07-16

Character conversion between CString string char* char in C++ (multiple methods)

Let's start by explaining what the three mean

CString is a very useful data type. They largely simplify many operations in MFC (for the MFC framework) and make it much easier to do string manipulation in MFC. Need to include the header file #include <>

C++ is strings, which are more powerful. To use the string class in standard C++, you must include #include <string> // Note that it is <string>, not <>, and that the ones with .h are header files in C. Char * is specifically used to refer to strings that end with '\0'.

The following methods are used to perform the conversion:

// : Defines the entry point to the console application.
//

#include ""
#include<iostream>
#include<>
#include<string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	//This method is applicable to“multibyte” Otherwise, there will be'strcpy' : cannot convert parameter 2 from 'unsigned short *' to 'const char *'
	/*CString str("Hello zzu");
	cout<<"the CString is "<<str<<endl;
	char a[100];
	strcpy(a,str);
	cout<<"the convert to char * is "<<a<<"(char *)"<<endl;*/

	//CString to string
	//  CString c_str1("Hello Zhengzhou University");
	//string str;
	//str=c_str1.GetBuffer(0);
	//c_str1.ReleaseBuffer(); //otherwise there is no release of the space occupied by the buffer
	//cout<<str<<endl;
	//cout<<"\n"<<c_str1<<endl;

	//string to CString
	/*string str1("Hello College of Information Engineering");
CString c_str2;
c_str2=str1.c_str(); //c_str(): generate a const char* pointer to an array terminated by a null character.
cout<< "the CString is"<<c_str2<<endl.
cout<< "the string is"<<str1<<endl;*/

	//string to const char* conversion
	//Method I:
	//string str2("Hello College of Information Engineering");
	//const char * str3; //constant pointer
	//str3=str2.c_str();
	//cout<<"string  is  "<<str2<<endl;
	//cout<<"const char is "<<str3<<endl;
	

	//Method II.
 // /* string str("Hello College of Information Engineering");
	//const char * c_str;
	//c_str=();
	//cout<<"string is  "<<str<<endl;
	//cout<<"const char is"<<c_str<<endl;*/
	
	
	
	//string directly to char*
	///*string s1 = "abcdefg";
	//char *data;
	//int len = ();
	//data = (char *)malloc((len)*sizeof(char));
	//(data,len,0);
	//cout<<len<<endl;
	//cout<<data<<endl;*/
	
  
    
	Usage of //()
	  //size_t length;
  //  char buffer[8];
  // string str("Test string......");
  //  
  // length=(buffer,7,6); // count back 7 from buffer6, which is equivalent to [ buffer[6], buffer[6+7] )
  // buffer[length]='\0'; // adding '\0' makes the buffer go as far as buffer[length];
 
  // cout <<"buffer contains: " << buffer <<endl;
  //char * to string


	//char * to string
  /* char * c_str="zzu";
	string str(c_str);
	cout<<"the c_str "<<c_str<<endl;
	cout<<"the string is"<<str<<"and length is "<<()<<endl;*/


	//char a[]="asd";
	//cout<<strlen(a)<<endl; //why is it showing 3, isn't there a \0?

	//char * to CString
  
	////char * c_str1="zzu";
	////CString str; //can be converted directly, since there is overloading of CString (applicable in multi-byte character sets)
	////("%s",c_str1);
	////cout<<"the c_str1 is"<<c_str1<<endl;	
	////cout<<"the CString is"<<str<<endl;



	// Method 1: Conversion using API: WideCharToMultiByte (used, valid)
   //CString str= CString("This is an example!");
   //int n = (); // by character, length of str
   //int len = WideCharToMultiByte(CP_ACP,0,str,n,NULL,0,NULL,NULL);//calculate str length by Byte
   //char *pChStr = new char[len+1];// byte by byte
   //WideCharToMultiByte(CP_ACP,0,str,n,pChStr,len,NULL,NULL);//WideCharToMultiByte Encoding
   // pChStr[len] = '\0';// don't ignore the end end flag
   // Remember to delete []pChStr when you're done with it to prevent memory leaks.
	return 0;
}

At the same time, it should be noted that we write the program in Pingcheng, it is best to figure out our compilation environment in the encoding, different encoding can lead to some character conversion failure, when we program the beginning, we have to think about which encoding in which encoding, so as not to end up with a change in the encoding mode, the code but a lot of errors (a headache), such as the sqlite database of the Chinese characters messy code! The problem is due to the encoding and the default encoding in the database is not consistent. This must be borne in mind when we write the program.

MFC char *, string and CString between the conversion of additional

I. Convert CString class to char * (LPSTR) type

Method 1, use forced conversion. Example:

CString theString( "This  is a test" );
LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

Method 2, using strcpy. e.g.:

CString theString( "This  is a test" );
LPTSTR lpsz = new TCHAR[()+1];
_tcscpy(lpsz, theString);

Method 3, using CString::GetBuffer. for example:

CString s(_T("This is a  test "));
LPTSTR p = ();
// Add the code to use p here
if(p != NULL) *p =  _T('\0');
();
// Release it when you're done using it so that you can use other CString member functions.

CString str = "ABCDEF";
char *pBuf = str,GetBuffer( 0 );
();

II. string to char*

string is one of the c++ standard libraries that encapsulates operations on strings.
There are 3 ways to convert string to char*:
1. data(), returns an array of strings without "\0".
As:
string str="abc";
char  *p=();
2. c_str Returns an array of strings with "\0".
For example: string str="gdfd";
    char *p=str.c_str();
3 copy
for example
string  str="hello";
char p[40];
(p,5,0); //Here 5, represents the copying of several characters, and 0 represents the position of the copying
*(p+5)='\0'; //To add the terminator manually
cout < < p;

Convert string to other data types

temp="123456";
1) Short Integer (int)
i =  atoi(temp);
(2) long integer (long)
l =  atol(temp);
3) Floating point (double)
d =  atof(temp);
string s; d= atof(s.c_str());
4) BSTR variables
BSTR bstrValue = ::SysAllocString(L "programmer");
... //// Completes the use of bstrValue
SysFreeString(bstrValue);
5) CCombsTR variable
Variables of type CComBSTR can be directly assigned values
CComBSTR  bstrVar1("test");
CComBSTR bstrVar2(temp);
6) _bstr_t variable
Variables of type _bstr_t can be directly assigned values
_bstr_t  bstrVar1("test");
_bstr_t bstrVar2(temp);

IV. Char* to string conversion

To convert a char to a string, you can use string s(char *).

V. string to CString

("%s",  string.c_str());

VI. char to CString

("%s", char*);

VII. CString -> string

string  s(()); 
GetBuffer() must be followed by ReleaseBuffer(), otherwise the space occupied by the buffer is not released.

VIII. CString interconvert int

To convert characters to integers, you can use atoi, _atoi64, or atol.
And to convert numbers to CString variables, you can use the Format function of CString. For example

CString s; 
int i = 64; 
("%d", i)