For example in Python:
name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")
This would output: “My name is John and I am 30 years old.”
Is there a similar way to format strings in C++? I know about std::stringstream and std::printf, but they seem more verbose and error-prone compared to Python’s f-strings.
Is there a way to achieve similar string formatting in C++ like in Python? If so, what are the best practices and libraries to use?
2
You can’t embed variable names in string literals to have them mapped to variables as you can in python. You need to supply the variables as arguments to the function you use separately.
The most similar way would be to use std::print
which is available since C++23:
#include <print>
#include <string>
int main() {
std::string name = "John";
int age = 30;
std::print("My name is {} and I am {} years old.n", name, age);
}
In C++20, you could use std::format
instead:
#include <format>
#include <iostream>
#include <string>
int main() {
std::string name = "John";
int age = 30;
std::cout << std::format("My name is {} and I am {} years old.n", name, age);
}
11