I have to format std::string with sprintf and send it into file stream. How can I do this?
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.