std::string formatting like sprintf

前端 未结 30 3143
野趣味
野趣味 2020-11-22 04:42

I have to format std::string with sprintf and send it into file stream. How can I do this?

30条回答
  •  清歌不尽
    2020-11-22 05:29

    Below slightly modified version of @iFreilicht answer, updated to C++14 (usage of make_unique function instead of raw declaration) and added support for std::string arguments (based on Kenny Kerr article)

    #include 
    #include 
    #include 
    #include 
    
    template 
    T process_arg(T value) noexcept
    {
        return value;
    }
    
    template 
    T const * process_arg(std::basic_string const & value) noexcept
    {
        return value.c_str();
    }
    
    template
    std::string string_format(const std::string& format, Args const & ... args)
    {
        const auto fmt = format.c_str();
        const size_t size = std::snprintf(nullptr, 0, fmt, process_arg(args) ...) + 1;
        auto buf = std::make_unique(size);
        std::snprintf(buf.get(), size, fmt, process_arg(args) ...);
        auto res = std::string(buf.get(), buf.get() + size - 1);
        return res;
    }
    
    int main()
    {
        int i = 3;
        float f = 5.f;
        char* s0 = "hello";
        std::string s1 = "world";
        std::cout << string_format("i=%d, f=%f, s=%s %s", i, f, s0, s1) << "\n";
    }
    

    Output:

    i = 3, f = 5.000000, s = hello world
    

    Feel free to merge this answer with the original one if desired.

提交回复
热议问题