how convert CString to char *?

  • Thread starter Thread starter Neo
  • Start date Start date
how convert CString to char *?

For VC2005
http://msdn2.microsoft.com/en-us/library/awkwbzyc.aspx

For VC2003 you'd do the same. except you won't use the 'safe' runtime
functions.
CString theString( "This is a test" );
LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
_tcscpy(lpsz, theString);
//... modify lpsz as much as you want

--

Kind regards,
Bruno van Dooren
(e-mail address removed)
Remove only "_nos_pam"
 
Neo said:
how convert CString to char *?

regards,
Mohammad Omer Nasir

Mohammad:

Very possibly, you only need a const char*, in which case you can just do

CString str("Hello world\n");
const char* s = str;

David Wilkinson
 
how convert CString to char *?

There are already 3 answers, all good, but depends what you need.

If you need a copy that you want to change, then go with new/_tcscpy [Bruno]
If you need to change the string in place, then GetBuffer() [Tom]
If you need read-only access to the buffer, then use implicit cast [David]


But I would like to add a special case: if the application is Unicode, then
the CString is also Unicode, meaning you don't get char*, but wchar_t*.
In this case David's code will not compile.

If you really need char* even for a Unicode application,
then you need to do a conversion to the (most likely) ANSI code page.
You can use WideCharToMultiByte or the T2A conversion macro.
But you have to make sure this is what you really need, because you will
damage all characters outside the code page used for conversion.
 
thanks gays for answer.

regards,
Mohammad Omer Nasir.


Mihai N. said:
how convert CString to char *?

There are already 3 answers, all good, but depends what you need.

If you need a copy that you want to change, then go with new/_tcscpy [Bruno]
If you need to change the string in place, then GetBuffer() [Tom]
If you need read-only access to the buffer, then use implicit cast [David]


But I would like to add a special case: if the application is Unicode, then
the CString is also Unicode, meaning you don't get char*, but wchar_t*.
In this case David's code will not compile.

If you really need char* even for a Unicode application,
then you need to do a conversion to the (most likely) ANSI code page.
You can use WideCharToMultiByte or the T2A conversion macro.
But you have to make sure this is what you really need, because you will
damage all characters outside the code page used for conversion.
 
Back
Top