std::string formatting like sprintf

前端 未结 30 2962
野趣味
野趣味 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条回答
  •  Happy的楠姐
    2020-11-22 05:13

    Based on the answer provided by Erik Aronesty:

    std::string string_format(const std::string &fmt, ...) {
        std::vector str(100,'\0');
        va_list ap;
        while (1) {
            va_start(ap, fmt);
            auto n = vsnprintf(str.data(), str.size(), fmt.c_str(), ap);
            va_end(ap);
            if ((n > -1) && (size_t(n) < str.size())) {
                return str.data();
            }
            if (n > -1)
                str.resize( n + 1 );
            else
                str.resize( str.size() * 2);
        }
        return str.data();
    }
    

    This avoids the need to cast away const from the result of .c_str() which was in the original answer.

提交回复
热议问题