How to format strings in C++?

In C++, you can format strings using either std::stringstream or the printf function.

Utilize std::stringstream:

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    ss << "Number: " << num << ", Float: " << f << ", String: " << str;

    std::string formatted_str = ss.str();
    std::cout << formatted_str << std::endl;

    return 0;
}

By utilizing the printf function:

#include <iostream>
#include <cstdio>

int main() {
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    char buffer[100];
    std::sprintf(buffer, "Number: %d, Float: %.2f, String: %s", num, f, str.c_str());

    std::string formatted_str = buffer;
    std::cout << formatted_str << std::endl;

    return 0;
}

This allows you to format strings using std::stringstream or printf function.

bannerAds