Solution_1:
Modern C++ makes this super simple.
C++20
General case
C++20 introduces std::format, which allows you to do exactly that. It uses replacement fields similar to those in python:
#include <iostream>
#include <format>
int main() {
std::cout << std::format("Hello {}!\n", "world");
}
Check out the full documentation! It's a huge quality-of-life improvement.
Solution_2:
in this case
using nlohmann/json (https://github.com/nlohmann/json)
#include <nlohmann/json.hpp>
// for convenience
using json = nlohmann::json;
// create an empty structure (null)
json j;
// add a number that is stored as double (note the implicit conversion of j to an object)
j["pi"] = 3.141;
// add a Boolean that is stored as bool
j["happy"] = true;
// add a string that is stored as std::string
j["name"] = "Niels";
// add another null object by passing nullptr
j["nothing"] = nullptr;
",{,}, or similar character that requires json escaping. If someone on my team put out a pull request where they were manually formatting a JSON or XML blob, I would immediately tell them to go use one of the standard parsing/formatting libraries we already have in our code base that guarantees escaping. Google for "json library" or similar. Millions of libs avaialble.