RANOK
RANOK

Reputation: 74

Create string with parameters c++ | formatting c++20

const char* email = "[email protected]";
const char* password = "123456";
          data.add(R"({
             "name": "{*MY_EMAIL_HERE*}",
             "password": "{*MY_PASSWORD_HERE*}",
             "date": { "day": 20, "month": "Apr" }
          })");

I'm looking for fast way to do it like u do in C language with printf("%s", myString);

Upvotes: 1

Views: 92

Answers (1)

RANOK
RANOK

Reputation: 74

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;

Upvotes: 3

Related Questions