Avatar ·

String formatting in C++ like sprintf: modern and safe ways

Hi! I've been writing in C++ recently and encountered a problem with string formatting. Previously in C I used sprintf:
char buffer[256];
sprintf(buffer, "Hello, %s! You are %d years old.", name.c_str(), age);
But in C++ with std::string this is inconvenient: you have to carry c_str(), a fixed-size buffer, and sprintf is unsafe (buffer overflow possible). I tried snprintf — better, but still cumbersome. I know there is std::stringstream, but it's too verbose:
std::stringstream ss;
ss << "Hello, " << name << "! You are " << age << " years old.";
std::string result = ss.str();
This is fine for simple cases, but when you need to format numbers (field width, precision, hex), writing pseudo-code becomes painful. For example, how to output