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

  • 2020-05-30 20:47:33
  • OfStack

First, explain what the three mean

CString is a useful data type. They greatly simplify many operations in MFC (for the MFC framework), making MFC a lot easier to do with strings. The header file #include needs to be included < afx.h >

C++ is a string, which is quite powerful. To use the standard C++ string class, you must include #include < string > / / note is < string > , not < string.h > , with.h is the header file in the C language. Char * is used specifically for strings ending with '\0'.

The following methods are used to perform the conversion:


// CharConvert.cpp :  Define the entry point for the console application. 
//

#include "stdafx.h"
#include<iostream>
#include<afx.h>
#include<string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	// This method applies to "multi-byte"   Otherwise it will happen '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  Converted to string
	//  CString c_str1("Hello Zhengzhou University");
	//string str;
	//str=c_str1.GetBuffer(0);
	//c_str1.ReleaseBuffer();  // Otherwise there is no free space for the buffer 
	//cout<<str<<endl;
	//cout<<"\n"<<c_str1<<endl;

	//string  Converted to CString
	/*string str1("Hello College of Information Engineering");
	CString c_str2;
	c_str2=str1.c_str(); //c_str() Generated by: 1 a const char* Pointer to an array terminated with null characters. 
	cout<<"the CString is "<<c_str2<<endl;
	cout<<"the string is "<<str1<<endl;*/

	//string Converted to const char*
	// methods 1 : 
	//string str2("Hello College of Information Engineering");
	//const char * str3;  // A constant pointer 
	//str3=str2.c_str();
	//cout<<"string  is  "<<str2<<endl;
	//cout<<"const char is "<<str3<<endl;
	

	// methods 2:
 // /* string str("Hello College of Information Engineering");
	//const char * c_str;
	//c_str=str.data();
	//cout<<"string is  "<<str<<endl;
	//cout<<"const char is"<<c_str<<endl;*/
	
	
	
	//string  Convert directly to char*
	///*string s1 = "abcdefg";
	//char *data;
	//int len = s1.length();
	//data = (char *)malloc((len)*sizeof(char));
	//s1.copy(data,len,0);
	//cout<<len<<endl;
	//cout<<data<<endl;*/
	
  
    
	//string.copy() The use of the 
	  //size_t length;
  //  char buffer[8];
  // string str("Test string......");
  //  
  // length=str.copy(buffer,7,6);    // from buffer6 , the number in the future, 7 Student: one, equivalent to [ buffer[6], buffer[6+7]  ) 
  // buffer[length]='\0';            // add '\0' make buffer As to the buffer[length] So far; 
 
  // cout <<"buffer contains: " << buffer <<endl;
  //char *  Converted 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 "<<str.length()<<endl;*/


	//char a[]="asd";
	//cout<<strlen(a)<<endl; // Why is it shown 3 , not have 1 a \0 ? 

	//char *  to CString
  
	////char * c_str1="zzu";
	////CString str; // It can be converted directly because CString There is heavy ( For use in multi-byte character sets )
	////str.Format("%s",c_str1);
	////cout<<"the c_str1 is"<<c_str1<<endl;	
	////cout<<"the CString is"<<str<<endl;



	// methods 1 Use: API : WideCharToMultiByte Convert (used, valid) 
   //CString str= CString("This is an example!");
   //int n = str.GetLength(); // By character, str The length of the 
   //int len = WideCharToMultiByte(CP_ACP,0,str,n,NULL,0,NULL,NULL);// According to the Byte To calculate str The length of the 
   //char *pChStr = new char[len+1];// In bytes 
   //WideCharToMultiByte(CP_ACP,0,str,n,pChStr,len,NULL,NULL);// Wide byte conversion to multi-byte encoding 
   // pChStr[len] = '\0';// Don't ignore the end of the end sign 
   // Remember when you run out delete []pChStr, Prevent memory leaks 
	return 0;
}

At the same time, it is important to note that when we write programs in pp.47-53, best figure out the way we compile environment of coding, different ways of encoding can lead to 1 character conversion fails, when we start programming, will want to have, in which coding mode so as to avoid the last appeared in encoding, code has a lot of mistakes (very troubling), such as the Chinese characters garbled in sqlite database problem is due to the encoding, and database of the default encoding is not 1. This is something to keep in mind when we write programs.

char* in MFC,string and CString complement the conversion

1. Convert the CString class to the char*(LPSTR) type

Method 1, use a cast. Such as:

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

Method 2, strcpy. Such as:

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

Method 3, CString::GetBuffer. Such as:

CString s(_T("This is a test "));
LPTSTR p = s.GetBuffer();
// add code that USES p here
if(p != NULL) *p = _T('\0');
s.ReleaseBuffer();
// release in time after use so that other CString member functions can be used

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

2. Turn string char *

string is one of the standard c++ libraries that encapsulates operations on strings
There are three ways to convert string to char* :
1. data(), returns an array of strings without "\0"
Such as:
string str="abc";
char *p=str.data();
2.c_str returns an array of strings with "\0"
Such as: string str = "gdfd";
char *p=str.c_str();
3 copy
Such as
string str="hello";
char p[40];
str. copy (p, 5, 0); // in this case, 5 is the copy of several characters, and 0 is the copy position
* (p + 5) = '\ 0'; // you need to add the ending sign manually
cout < < p;

3. Convert the string string to other data types

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

4. Char* converted to string

If you want to convert 1 char to string, you can use string s(char *);

5. Turn string CString

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

6. Turn CString char

CString.format("%s", char*);

7. CString - > string

string s(CString.GetBuffer());
GetBuffer() must have ReleaseBuffer() after 1, otherwise there will be no free space for the buffer.

8. CString to int

To convert a character to an integer, you can use atoi, _atoi64, or atol.
To convert the number to the CString variable, CString's Format function can be used. Such as


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


Related articles: