岚天逸见

#微码分享#C++变参字符串格式化函数format_string

在C和C++中,变参格式化函数虽然非类型安全,但却十分便利,因为得到广泛使用。对于常见的size_t类型要用“%zu”,ssize_t用”%zd“,int64_t用“% ”PRId64,uint64_t用“% ”PRIu64,long用"%ld",long long用"%lld",示例:
const int64_t datetime = INT64_C(20190124144930);
​printf("datetime: %" PRId64"\n", datetime);
注意在PRId64前保留一个空格,以避免编译警告

format_string源代码链接:
https://github.com/eyjian/r3c/blob/master/utils.cpp
​https://github.com/eyjian/libmooon/blob/master/src/utils/string_utils.cpp​​​
​​
format_string源代码:

复制代码
// snprintf()第2个参数的大小,要求包含结尾符'\0'
// snprintf()的返回值是期望大小,不包含结尾符'\0',
// 下面假设snprintf()的第二个参数值为10,则:
// 1) 当str为"abc"时,它的返回值的大小是3,"abc"的字符个数刚好是3;
// 2) 当str为"1234567890"时,它的返回值大小是10,"1234567890"的字符个数刚好是10;
// 3) 当str为"1234567890X"时,它的返回值大小是11,"1234567890X"的字符个数刚好是11。
//
// int asprintf(char **strp, const char *fmt, ...);
std::string format_string(const char* format, ...)
{
    size_t size = 4096;
    std::string buffer(size, '\0');
    char* buffer_p = const_cast<char*>(buffer.data());
    int expected = 0;
    va_list ap;

    while (true)
    {
        va_start(ap, format);
        expected = vsnprintf(buffer_p, size, format, ap);

        va_end(ap);
        if (expected>-1 && expected<=static_cast<int>(size))
        {
            break;
        }
        else
        {
            /* Else try again with more space. */
            if (expected > -1)    /* glibc 2.1 */
                size = static_cast<size_t>(expected + 1); /* precisely what is needed */
            else           /* glibc 2.0 */
                size *= 2;  /* twice the old size */

            buffer.resize(size);
            buffer_p = const_cast<char*>(buffer.data());
        }
    }

    // expected不包含字符串结尾符号,其值等于:strlen(buffer_p)
    return std::string(buffer_p, expected>0?expected:0);
}
复制代码

 

posted on   岚天逸见  阅读(1094)  评论(0编辑  收藏  举报

编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

导航

统计信息

点击右上角即可分享
微信分享提示