Link to home
Start Free TrialLog in
Avatar of justinng
justinng

asked on

Question on converting CString to string

Hi there,
         How can I convert a CString to string (char *str or
char str[20])??

Any help offered is very much appreciated!!!
Avatar of wyy_cq
wyy_cq

function char* CString::GetBuffer(int) will help you,
but when you call this function the cstring instance's buffer length will be fixed.
you need to call CString::ReleaseBuffer(...);when you finish the operation.

// example for CString::GetBuffer
CString s( "abcd" );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif
LPTSTR p = s.GetBuffer( 10 );
strcpy( p, "Hello" );    // directly access CString buffer
s.ReleaseBuffer( );
#ifdef _DEBUG
afxDump << "CString s " << s << "\n";
#endif

Also don't forget that CString automatically casts to
const char* so it is fairly easy to include in an argument
list where a const char* was expected
i.e.

CString sString("abcd");
char zMyString[20];

strcpy(zMyString, sString); //as long as you are sure it will fit

also in the case of varargs you can explicity cast it

TRACE("sString: %s\n", (LPCSTR)sString);

Avatar of justinng

ASKER

Hi thanks but I prefer GGRUNDY's solution...
auto convert it only can be converted int const char*.
if you want to do this :
CString s;
sprintf(s,"%d",100);

you will not be permitted.
GetBuffer(...) can return "char*" not the "const char*" .

i hope you shall browse the sample code again.
CString s( "abcd" );
LPTSTR p = s.GetBuffer( 10 );
strcpy( p, "Hello" );    // directly access CString buffer
s.ReleaseBuffer( );

your question is "convert to string" not "convert to const string".
so i think my answer is correct.



Hey justinng, I'm sure you are probably trying to do
me a favour by rejecting wyy_cq's answer,
BUT points ain't really the point. Helping is the
point. Please accept Wyy_cq's answer and let's
get this puppy off the front page and into the
solved basket.
heheee... okie... so I'll be waiting for any one of you to throw this puppy into the solved basket then... ha!
Thanks GGRUNDY!!!
anyway thanks for letting me know the 2 different solutions for "convert to string" and "convert to const string". Thanks to you all!!! Now at least I know the difference :)
ASKER CERTIFIED SOLUTION
Avatar of stkul
stkul

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