std::string formatting like sprintf

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

    template
    std::string string_format(const char* fmt, Args... args)
    {
        size_t size = snprintf(nullptr, 0, fmt, args...);
        std::string buf;
        buf.reserve(size + 1);
        buf.resize(size);
        snprintf(&buf[0], size + 1, fmt, args...);
        return buf;
    }
    

    Using C99 snprintf and C++11

提交回复
热议问题