MIKE2S
asked on
CSTRING into normal char[10]
Hello,
I think it is simple
How can I convert a CSTRING to char
I think it is simple
How can I convert a CSTRING to char
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.GetBuffe r(0),ptrCs tring);
will copy an uninitialised char array onto the CStrings buffer which is unlikely to be what you want.
Note strcpy looks like:
strcpy(char* dest, char* src)
so:
char ptrCstring[10];
strcpy(MFC_string.GetBuffe
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.
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).
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 )
>
>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.
ASKER
I accept jason clarks answer. Works fine thanks to all!
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(-
--------------------------
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.GetBuffe
MFC_string.ReleaseBuffer()