
STL strings & printf-type formatting
Rod,
Here is a rough example of a global function which takes a std::string, a
format string, and a variable number of arguments and formats the string
appropriately. This should suit your needs. You could always write
another one which takes a std::wstring
(On the other hand, if you're really looking for a std::basic_string
derivative which has this CString like functionality, you could also try
something I wrote a while back
http://home.earthlink.net/~jmoleary/stdstring.htm)
Joe O'
void FormatString(std::string& str, LPCSTR* szFormat, ...)
{
va_list argList;
va_start(argList, szFormat);
FormatStringV(str, szFormat, argList);
va_end(argList);
}
#define MAX_FMT_TRIES 5 // #of times we try if 2048 chars isn't big
enough
#define FMT_BLOCK_SIZE 2048 // amount of extra memory we'll add above
2048 each try
void FormatStringV(std::string& str, LPCSTR szFormat, va_list argList)
{
va_list argListSave = argList;
// We'll use the _vsntprintf function, assuming FMT_BLOCK_SIZE
characters.
int nTriesLeft = MAX_FMT_TRIES;
int nUsed = -1;
char* pBuf;
int nChars = 0;
// Keep looping until we succeed or we have exhausted the number of
tries
do
{
nChars += FMT_BLOCK_SIZE; // number of TCHARS in the string
pBuf = reinterpret_cast<LPCSTR>(_alloca(nChars));
// Now try the actual formatting.
nUsed = _vsntprintf(pBuf, nChars, szFormat, argListSave);
if ( nUsed >= 0 )
str = pBuf;
} while ( nUsed < 0 && --nTriesLeft > 0);
va_end(argListSave);
}
}
Quote:
> Is there an STL algorithm or other such template that will allow
printf-type
> formatting of std::string & std::wstring objects.
> What I would like to do is some like:-
> std::string strAge;
> strAge.format("%03d", nAgeVar);
> or more likely
> std::string strAge;
> format(strAge, "%03d", nAgeVar);
> Rod Paterson