Sujet : Re: Tabs As Syntax
De : ldo (at) *nospam* nz.invalid (Lawrence D'Oliveiro)
Groupes : comp.os.linux.advocacyDate : 23. Mar 2024, 01:36:38
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <utl4m5$3700q$6@dont-email.me>
References : 1 2 3 4 5 6 7
User-Agent : Pan/0.155 (Kherson; fc5a80b8)
On Fri, 22 Mar 2024 08:20:11 -0400, Chris Ahlstrom wrote:
operator << is useful with std::ostringstream when you want to avoid
having deal with allocating enough output space. Still, I use this a
lot:
char temp[32];
snprintf(temp, sizeof temp, "We have %d idiots here", idcount);
Sometime a printf specification is just easier to read.
I wrote this a long time ago, for use in some projects in C++. You can
tell it was a long time ago, from the checking for glibc versions:
std::string string_printf
(
const char * Format,
...
)
/* does an sprintf of its remaining arguments according to Format,
returning the formatted result. */
{
std::string Result;
char * TempBuf;
ulong TempBufSize;
TempBuf = nil;
TempBufSize = 128; /* something reasonable to begin with */
for (;;)
{
TempBuf = (char *)malloc(TempBufSize);
if (TempBuf == nil)
break;
va_list Args;
va_start(Args, Format);
const long BufSizeNeeded = vsnprintf(TempBuf, TempBufSize, Format, Args);
/* not including trailing null */
va_end(Args);
if (BufSizeNeeded >= 0 and BufSizeNeeded < TempBufSize)
{
/* the whole thing did fit */
TempBufSize = BufSizeNeeded; /* not including trailing null */
break;
} /*if*/
free(TempBuf);
if (BufSizeNeeded < 0)
{
/* glibc < 2.1 */
TempBufSize *= 2; /* try something bigger */
}
else
{
/* glibc >= 2.1 */
TempBufSize = BufSizeNeeded + 1;
/* now I know how much I need, including trailing null */
} /*if*/
} /*for*/
if (TempBuf != nil)
{
Result.append(TempBuf, TempBufSize);
free(TempBuf);
} /*if*/
return
Result;
} /*string_printf*/