How to convert CString to char* or LPTSTR?

17 12 2008


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. 😉

cstringtolptstr


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.

Advertisements

Actions

Information

4 responses

18 12 2008
ViT

You also can use
...
char * pString = String.c_str();
...

18 12 2008
Jijo.Raj

Well, ViT, the c_str() function is for std::string not for CString.

Regards,
Jijo.

28 02 2009
Saleem

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

28 02 2009
Jijo.Raj

Hello Saleem,

Try using MultiByteToWideChar(). This link – will help you.

Regards,
Jijo.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s




%d bloggers like this: