Re: CString to const char*
NickP wrote:
I am having some really strange issues with the CString class...
For some reason it will not convert to const char* automatically, if I
try manually I just end up with a screwed up ASCII string still containing
0 bytes from the UNICODE equivilent.
CString contains TCHARs, which, as Viktor said, either map to char or
wchar_t. If you keep using TCHAR all the way through, things fit together
nicely.
char *pBuffer = new char[iString.GetLength()];
Typically, you need length+1 characters, for the terminating null.
pBuffer = (char*)iString.GetBuffer(sizeof(pBuffer));
Two things here:
1. You discard the content of pBuffer, leading to a memory leak.
2. You are using a brote-force C-style cast. Never use those, always use C++
casts. Also, never cast unless you exactly know what you are doing.
Strange thing is my CString class is within the WTL namespace, is
there more than one implementation of CString available?
CString moved from the global namespace into the WTL namespace. If you use
it via the MFC, it get imported into the global namespace again, AFAICT.
Further, it became a template(!) based on the character type. Also, newer
WTL/MFC provide CStringA and a CStringW class, which are the char and
wchar_t versions. For your problem, you might want to choose CStringA.
What would be the best object to use for string handling, I thought
this class was okay but have read sources on the net that say
std::string is better...
Define 'better' before making such statements. IMHO the only undisputable
advantages of std::string are that it is portable (because standard C++)
and that it doesn't change its meaning depending on whether _UNICODE is
defined.
Preferably I'd like to just use CString and convert it nicely...
How so? If said string contains a Euro sign and your local codepage doesn't
have a representation for that you can't convert it. If you know that this
can't happen you could use a char-based string like std::string or
CStringA, otherwise you will have to stay with a wchar_t based one and
perhaps rethink your requirement of converting to char.
Uli