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.
Syntax of string interpolation starts with a '$' symbol and expressions are defined within a bracket {} using the following syntax. Where: interpolatedExpression - The expression that produces a result to be formatted.
As the colon (":") has special meaning in an interpolation expression item, to use a conditional operator in an interpolation expression, enclose that expression in parentheses. string name = "Horace"; int age = 34; Console. WriteLine($"He asked, \"Is your name {name}?\ ", but didn't wait for a reply :-{{"); Console.
Structure of an interpolated string in C# In programming, an interpolated string is a literal string that contains interpolation expressions. Each time an interpolated string is resolved to a result string, the interpolation expressions are replaced with string representations of the results of the expressions.
In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With