std::string formatting like sprintf

前端 未结 30 3135
野趣味
野趣味 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:16

    I realize this has been answered many times, but this is more concise:

    std::string format(const std::string fmt_str, ...)
    {
        va_list ap;
        char *fp = NULL;
        va_start(ap, fmt_str);
        vasprintf(&fp, fmt_str.c_str(), ap);
        va_end(ap);
        std::unique_ptr formatted(fp);
        return std::string(formatted.get());
    }
    

    example:

    #include 
    #include 
    
    int main()
    {
        std::random_device r;
        std::cout << format("Hello %d!\n", r());
    }
    

    See also http://rextester.com/NJB14150

提交回复
热议问题