Інтерполяція рядків

C++:
Інтерполяція рядків

How to:

Як це зробити:

In C++, you can use std::format from C++20 to interpolate strings easily.

#include <iostream>
#include <format>

int main() {
    int age = 30;
    std::string name = "Oleksiy";
    std::string greeting = std::format("Hello, {0}! You are {1} years old.", name, age);
    
    std::cout << greeting << std::endl;
    
    return 0;
}

Output:

Hello, Oleksiy! You are 30 years old.

Deep Dive:

Поглиблений огляд:

Before C++20, you’d typically use stream insertion operators (<<) or sprintf. These methods can be error-prone and less readable. std::format was introduced to simplify string formatting, inspired by Python’s str.format() and C#’s string interpolation.

Alternatives to std::format include the Boost Format library or using third-party libraries like {fmt}. Internally, std::format uses a format string that contains replacement fields surrounded by curly braces which match the arguments by order or name.

See Also:

Дивіться також: