Link to home
Start Free TrialLog in
Avatar of Trickster
Trickster

asked on

Best way to convert a CString to LPSTR

I have a Treeview control where I am adding a hierarchy of text items.
To insert items I use the TV_INSERTSTRUCT and the TreeCtrlItem.item.pszText to set text.
Since item.pszText needs a LPSTR I can either set it without using a variable, like 'TreeCtrlItem.item.pszText = "testItem";' but if I want to use a CString I have to convert that CString to LPSTR before using it.
What is the best way to do this?

I am currently using:
CString testString = "Cardboard";
int length = testString .GetLength();
char *cptr = testString .GetBuffer(length);
TreeCtrlItem.item.pszText = cptr;

Any other better ways?
Avatar of jkr
jkr
Flag of Germany image

Why not using

CString testString = "Cardboard";
TreeCtrlItem.item.pszText = (LPCTSTR) testString;

?

Avatar of Trickster
Trickster

ASKER

I tried that but got the message that TreeCtrlItem.item.pszText won't accept a LPCTSTR string - only LPSTR. I read in the help files that I can convert from LPCTSTR to LPSTR but that would mean two different conversions/casts and I don't know if that is a good choice.. That's one of the reasons I asked this question here.. :-)

// T
SOLUTION
Avatar of Dexstar
Dexstar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Why not something as simple as:

strcpy((char*)TreeCtrlItem.item.pszText , (LPCSTR)testString);

Obviously casting the TreeCtrlItem... to whatever it is...
char, wchar, tchar  so on....
Rather cast testString to LPCTSTR as previously noted...
Both seem to work.
Both Dextar and Freewell came up with a good answer so I doubled the points and then split them between the two..

// Trickster