Sujet : Re: Tabs As Syntax
De : OFeem1987 (at) *nospam* teleworm.us (Chris Ahlstrom)
Groupes : comp.os.linux.advocacyDate : 23. Mar 2024, 14:11:18
Autres entêtes
Organisation : None
Message-ID : <utmgt6$3k6u5$3@dont-email.me>
References : 1 2 3 4 5 6 7 8
User-Agent : slrn/1.0.3 (Linux)
Lawrence D'Oliveiro wrote this copyrighted missive and expects royalties:
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*/
You showed me yours. Let me show you mine. :-D
te<typename ... Args>
std::string string_format (const std::string & format, Args ... args)
{
std::string result;
size_t sz = std::snprintf(nullptr, 0, format.c_str(), args ...);
if (sz > 0)
{
std::unique_ptr<char []> buf(new char[sz + 1]);
std::snprintf(buf.get(), sz + 1, format.c_str(), args ...);
result = std::string(buf.get(), buf.get() + sz);
}
return result;
}
Note the variadic template.
In C++20 you can apparently write
#include <format>
std::string result = std::format("{} {}!", "Hello", "world");
-- You seek to shield those you love and you like the role of the provider.