Convert CString to char*

How to convert CString to char *
xtran888Asked:
Who is Participating?
 
Kent OlsenConnect With a Mentor Data Warehouse Architect / DBACommented:
Hi xtran888,

If all you want to do is get to the underlying string (and perhaps modify it) use the GetBuffer() method.  Here's a quick example.

CString s(_T("File.ext"));
LPTSTR p = s.GetBuffer();
LPTSTR dot = strchr(p, '.'); // OK, should have used s.Find...
if(p != NULL)
    *p = _T('\0');
s.ReleaseBuffer();



Good Luck,
Kent
0
 
IchijoCommented:
If you only need read-only access to the string, you can cast the CString to LPCSTR, if your environment is setup for ANSI (multi-byte) strings.

CString sTest("test");
const char *p = (LPCSTR)sTest;

If your build environment is set for Unicode, you'll get a type cast error because then the CString will compile to Unicode, and so you would need to add code to convert the string at runtime.
0
 
itsmeandnobodyelseCommented:
>>>> const char *p = (LPCSTR)sTest;

CString has a built-in cast operator for LPCSTR (== const char*). So you need no cast:

    CString s = "Hello";
    const char* psz = s;  // no cast needed

That means wherever a const char* (LPCSTR) was used you may use a CString instead.

Regards, Alex


0
 
itsmeandnobodyelseCommented:
>>> If your build environment is set for Unicode, you'll get a
>>> type cast error because then the CString will compile to Unicode
Using the TCHAR and LPCTSTR will solve that either for UNICODE or non-UNICODE.

  CString s = _T("Hello");   // makes either LPCSTR or LPCWSTR on right side
  LPTSTR p = new TCHAR[20];   // left side is either char* or wchar_t*
                                                 // TCHAR is either char or wchar_t
  _tcscpy(p, s);   // here you don't need to cast to LPCTSTR as it is built-in
                          // _tcscopy makes strcpy in case of non-UNICODE and wcscpy for UNICODE
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.