This is a very common problem. Let's record my solution below.
1. Convert CString to char []
Method 1: Use CString. GetBuffer (0) and strcpy
CString str; <br/> int len = str. getLength (); <br/> char * arr = new char [len]; <br/> strcpy (arr, str. getBuffer (0 ));
2. Convert char [] to CString
First, we will think of the following statement.
Char ch [7] = {'w', 'U', 'D', 'I', 'z', 'h', 'U '}; <br/> CString szTest (ch); <br/> AfxMessageBox (szTest );
Or
Char ch [7] = {'w', 'U', 'D', 'I', 'z', 'h', 'U '}; <br/> CString szTest; <br/> szTest. format ("% s", ch); <br/> AfxMessageBox (szTest );
However, the running results are:
Garbled characters are added at the end of the CString, and the length of the CString object obtained in the test is 7. Why? I think:
The CString object treats ch as a string. Therefore, when converting a char [] into a CString object, there are two processes:
1. First, convert char [] to char *, which generates garbled characters at the end of the string. The test is as follows:
Char ch [2] = {'A', 'B'}; <br/> TRACE ("% s", ch );
Debug and run the following command:
AB ironing t
2. Store the char * string in the CString objectCStringDataObject, which stores garbled data.
The garbled code we see appears.
Here, we may all know the cause of garbled characters.
Next we will solve the problem. This is naturally not a problem. Just assign the last bit of the array to '/0.
Char ch [3] = {'A', 'B', '/0'}; <br/> CString str; <br/> str. format ("% s", ch); <br/> AfxMessageBox (str );
The result is as follows:
Solve this problem