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
rxrazaAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
SteHConnect With a Mentor Commented:
CString str = "What ever you want";

char pString[200];

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

To get a pointer to a buffer you are aloowed to modify use
str.GetBuffer () ; // or GetBufferSetLength ()
and when finished using this buffer call
str.ReleaseBuffer (-1); // -1 if the string is 0 terminated else you need to supply the number of valid chars.
0
 
Jaime OlivaresSoftware ArchitectCommented:
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);
0
 
rxrazaAuthor Commented:
I like operator LPCTSTR() approach better.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
SteHCommented:
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.
0
 
Jaime OlivaresSoftware ArchitectCommented:
>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 *
0
 
SteHCommented:
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.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.