Link to home
Start Free TrialLog in
Avatar of MIKE2S
MIKE2SFlag for Germany

asked on

CSTRING into normal char[10]

Hello,
I think it is simple
How can I convert a CSTRING to char
ASKER CERTIFIED SOLUTION
Avatar of jasonclarke
jasonclarke

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Iexpert
Iexpert

Use the following member function:

LPTSTR GetBuffer( int nMinBufLength );

i.e

CString MFC_string = "Test";

char* ptrCstring = MFC_string.GetBuffer(10); //Need 10 bytes to work with
*ptrCstring = 'B';
MFC_string.ReleaseBuffer(-1); //-1 => ReleaseBuffer calls strlen to set the len

------------------------------------------------------
If you want a copy of the string use the strcpy function on the
returned pointer from GetBuffer, e.g.

CString MFC_string = "Test";

char ptrCstring[10];

strcpy(MFC_string.GetBuffer(0),ptrCstring);
MFC_string.ReleaseBuffer();


You don't need to use GetBuffer because CString has an operator LPCTSTR() that is called implicitly when you make the call to strcpy which is fine if all you want to do is copy the contents of the CString (modifying it is a different matter), although it does make sense to use the GetLength() method to make sure that it will fit.

Note strcpy looks like:

strcpy(char* dest, char* src)

so:

char ptrCstring[10];
strcpy(MFC_string.GetBuffer(0),ptrCstring);

will copy an uninitialised char array onto the CStrings buffer which is unlikely to be what you want.


CString string;
char ch[10];

////First, check the length of CString, if it is short than 10.

strcpy( ch,  (LPCTSTR)string );


Easy! I tested it.

strcpy(ch, string), won't work.
JHuang perhaps you should try to compile the example I gave in the answer.  You will find that both it and
strcpy(ch,string) work fine.  

The compiler must make the conversion implicitly, the C style cast is not required.  (Better to avoid C style casts all together if you can).
>Note strcpy looks like:
>
>strcpy(char* dest, char* src)

if it looked like the above the implicit conversion wouldn't happen.

actually strcpy looks like:
strcpy( char *s1, const char *s2 )


mmachie, you are correct, but the important thing was that the destination is the first parameter.
Avatar of MIKE2S

ASKER

I accept jason clarks answer. Works fine thanks to all!