Modern C++ makes this super simple. int main() { template
C++20
C++20 introduces std::format, which allows you to do exactly that. It uses replacement fields similar to those in python:
#include
#include
std::cout << std::format("Hello {}!n", "world");
}
Code from cppreference.com, CC BY-SA and GFDL
Check out the compiler support page to see if it's available in your standard library implementation. As of 2021-09-20, full support is only available in Visual Studio 2019 16.10, which was released on 2021-05-25. Clang 14 has partial support, which is tracked here. In all other cases, you can resort to the C++11 solution below, or use the {fmt} library, which has the same semantics as std::format.
C++11
With C++11s std::snprintf, this already became a pretty easy and safe task.
#include
#include
#include
std::string string_format( const std::string& format, Args … args )
{
int size_s = std::snprintf( nullptr, 0, format.c_str(), args … ) + 1; // Extra space for ‘