Gold mine of Visual C++ tricks!
How to convert CString to char* or LPTSTR?
![]()
Without a second thought, I can say that it will be one of the first problems that beginners face – How to convert a CString to LPTSTR. I’ve seen this question several times in forums. Well, i think the CString to LPTSTR conversion is just like this picture.

![]()
Well, you can use CString::GetBuffer() to access the internal buffer of CString. But one thing to take care is that – you should release the buffer by calling CString::ReleaseBuffer() after use. Check the code snippet below,
// Our CString object. CString String = "HelloWorld"; // Get the internal buffer pointer of CString. LPTSTR pString = String.GetBuffer( 0 ); ... // Use the pString and then release it. String.ReleaseBuffer();
![]()
Now get rid of that nasty error message – error C2664: ‘Hello’ : cannot convert parameter 1 from ‘class CString’ to ‘char *’.
![]()
Targeted Audience – Beginners.
| Print article | This entry was posted by Jijo Raj on December 17, 2008 at 9:43 pm, and is filed under MFC, Misc. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
You also can use
...
char * pString = String.c_str();
...
about 1 year ago
Well, ViT, the c_str() function is for std::string not for CString.
Regards,
Jijo.
about 1 year ago
Hi,,
I need this info.
I am using this code,
int length = data.GetLength(); // data is CString
USES_CONVERSION;
wchar_t *pwcharMessageBody = T2W(data.GetBuffer()); //stack overflow,This line // fails for large string
data.ReleaseBuffer();
This is working for most cases. But not working for very large string size.
Any help will be great.
Thanks,
Saleem
about 1 year ago
Hello Saleem,
Try using MultiByteToWideChar(). This link – will help you.
Regards,
Jijo.