-
February 14th, 2003, 03:45 AM
#1
Strings: How to convert a CString to a char*?
Q: How to convert a 'CString' to a 'char*'?
A: You will need this mostly to pass a 'CString' to a function that expects a 'char*'.
Code:
// Prototype of a function expecting a char*
void func(char* c);
CString csMyString = "Hello World";
// now call func()
char* str = csMyString.GetBuffer(csMyString.GetLength());
func(str);
// or directly
func(csMyString.GetBuffer(csMyString.GetLength()));
// if 'func()' modifies the passed char*, you must call
csMyString.ReleaseBuffer(-1);
Note:
- 'CString::GetBuffer()' will return a 'char*' only in non-UNICODE builds.
- 'CString' has an implicit operator to 'LPCTSTR'. In non-UNICODE builds, that is a 'const char*'. Do not use a cast hack like this:
Code:
func((char*)((LPCSTR) csMyString)); // BAD!!!!
- Do not call any other 'CString' member function on 'csMyString' between 'GetBuffer()' and 'ReleaseBuffer()'.
Last edited by Andreas Masur; July 24th, 2005 at 11:54 AM.
-
June 23rd, 2006, 03:12 AM
#2
Re: MFC String: How to convert a 'CString' to a 'char*'?
Starting VC++ 7.x, CString can be easily converted to a char* (or equivalent) for all possible build scenarios using conversion class CT2CA.
Like this -
Code:
CString csMyString = "Hello World";
CT2CA pszCharacterString (csMyString);
// Use pszCharacterString as a const char* or use it to copy into one
...Alternatively, using class CStringA -
Code:
CStringA pszCharacterString (csMyString);
// Use pszCharacterString as a char* or use it to copy into one
Last edited by Siddhartha; August 21st, 2006 at 06:26 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|