CString instead of LPCSTR
Posted
by Jon Zyzyck
on April 16th, 2002
Environment: VC6 SP4
Well, I've seen other people asking for a class like this, and I sure wanted one, so I finally wrote one.
SampleRoutine( (LPCSTR) csFMT( "Sample dynamic string count(%d) name(%s)", nAnInteger, szAZeroTerminatedString));
The Microsoft CString class provides a Format member routine which provides sprintf-type formatting, without the need to allocate a buffer. The class CString automatically calculates the size of the buffer required, and allocates it. A CString variable, however, must first be declared. This routine allows the CString Format member routine to be used, without needing to declare a CString.
Here is the sample code without using the "csFmt" routine:
CString csTemp; CsTemp.Format("Sample dynamic string count(%d) name(%s)", nAnInteger, szAZeroTerminatedString); SampleRoutine((LPCSTR) csTemp);
This method doesn't require any subclassing, and is only a short < 10 line routine.
CString csFMT(LPCSTR lpszFormat, ...) { CString csStr; va_list argList; va_start(argList, lpszFormat); csStr.FormatV(lpszFormat, argList); return csStr; }
Downloads
You can cut & paste code from above.