Search code examples
c++stringstring-interpolation

Simplest syntax for string interpolation in c++


I'm used to easy-to-read syntax for string interpolation like this in c# or JavaScript, so when I started learning c++ I expected that it will have a similar feature, but when googling for string interpolation in c++ I couldn't find anything like that.

In c# strings are interpolated like this:

$"My variable has value {myVariable}"

In JavaScript it looks like this:

`My variable has value ${myVariable}`

Inserting multiple values in different places in a string literal is such a common problem I'm sure there is some standard way of doing this in c++. I want to know what is the simplest way of doing this in c++ and how do people usually do it.


Solution

  • From c++20 you can use the <format> header to do something like this:

    auto s = std::format("My variable has value {}", myVariable);
    

    which is quite similar to how it's done in c# or JavaScript.