how convert CString to char *?

B

Bruno van Dooren

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"
 
T

Tom Serface

You can just call GetBuffer() if you want to access the string directly.

Tom
 
D

David Wilkinson

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
 
M

Mihai N.

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.
 
N

Neo

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top