CString/string difference and its conversion

When programming with MFC, the string we get from the dialog box using GetWindowText is of type CString, and CString is a class belonging to MFC. And some standard C/C++ library functions cannot directly operate on the CString type, so we often encounter the situation of converting the CString type to char* and other data types. Here's a summary of the memo here!
First of all, it should be clear that there is no string type in standard C. String is a class that extends string operations in standard C++. But we know that there is a header file string.h in standard C, and we need to distinguish clearly here, this string is not another string. The string.h header file defines some functions that we often use to manipulate strings, such as strcpy, strcat, strcmp, etc., but the operation objects of these functions are all strings pointed to by char*. The C++ string class operation object is a string type string. This class reloads some operators and adds some string operation member functions, making it more convenient to manipulate strings. Sometimes we want to use string strings and char* strings together, so the conversion of these two types will also be involved.

1. Conversion of CString
and string
string str = " ksarea " ;
CString cstr ( str . c_str ()) ; // or CString cstr(str. data()); at initialization cstr = str . c_str () ; or cstr = str . data () ; str = cstr . GetBuffer ( 0 ) //CString -> string cstr . format ( " %s " str .


c_str ()) //string->CString cstr . format ( " %s " str . data ()) //string->CString str  =  LPCSTR ( cstr ) //CString->string /*c_str( The difference between ) and data() is: the former returns a string with '/0', while the latter returns a string without '/0'*/


2. Conversion of CString and int
int i = 123 ;
CString str ;
str . format ( " %d " , i ) ; //int->CString 
other basic type conversions like i = atoi ( str ) ; //CString->int  also (atof, atol)
3. Conversion of char* and CString
CString cstr = " ksarea " ;
charptemp=cstr.getbuffer(0);
charstr;
strcpy(str,ptemp);//CString->char*cstr.releasebuffer(-1);char*str="lovesha";CStringcstr=str;//char*->CString string



Type cannot be directly assigned to CString
As for the conversion between int and float, string and char*, you can use forced conversion, or standard library functions. There are many conversion methods for CString and other types, but in fact, they all have the same goal. In one direction, the type is first converted to char* type, because char* is a bridge between different types. Once you get the char* type, it's very easy to convert to other types.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324522516&siteId=291194637