Link to home
Start Free TrialLog in
Avatar of rxraza
rxraza

asked on

Conversion from CString to char *s [ C style string]

Hi folks:

How do I convert  a CString to char *  [C- style string]? Thanks in advace
Avatar of Jaime Olivares
Jaime Olivares
Flag of Peru image

To simply point to the contents of the string:

CString str;
str = "test";

const char *strPtr;
strPtr = str;

If you want to copy contents to a char array:

char buffer[200];  // arbitrary size, you choose
strcpy(buffer, str);
ASKER CERTIFIED SOLUTION
Avatar of Member_2_1001466
Member_2_1001466

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 rxraza
rxraza

ASKER

I like operator LPCTSTR() approach better.
In the comment from  jaime_olivares the operator LPCTSTR () will be called as well. In his pointer assignment
strPtr= str;
it will be used implicitely.
>In the comment from  jaime_olivares the operator LPCTSTR () will be called as well. In his pointer assignment
It is not necessary because in my example strPtr is of type: const char *
Try to compile and gives you no warning

In steh comment:
strcpy (pString, str.operator LPCTSTR ()); // or use operator LPCTSTR () whenver you need a const C style string.

str.operator LPCTSTR(),   or better (LPCTSTR)str     is not necessary because second argument of strcpy expect a const char *, and LPCTSTR returns a const char *
The intention of my comment was to make rxraza aware that
CString str ("xxxx");
const char* pStr = str; // this line will call operator LPCTSTR () implicitly.

You don't need to write it explicitly. But since it is called why don't write it to show that a conversion/casting is happening here.