Simplest syntax for string interpolation in c++

Viewed 4845

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.

3 Answers

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.

FWIW, here is a C++11 safe version of sprintf that returns a std::string

template<typename... Args>
std::string Sprintf(const char *fmt, Args... args)
{
    const size_t n = snprintf(nullptr, 0, fmt, args...);
    std::vector<char> buf(n+1);
    snprintf(buf.data(), n+1, fmt, args...);
    return std::string(buf.data());
}

You can then do this:

float var = 0.123f;
std::string str = Sprintf("My variable has value %0.4f\n", var);

I like @cigien's answer if you are using C++20.

A possible way, particularly in embedded environment, is to utilize the C standard library:

#include <cstdio>

...
printf("My variable is %s\n", myVariable)
...

myVariable has to be a char*. For C++ strings, myVariable.c_str() should be used.

Related