C++ String Formatting Guide

In C++, there is no built-in format function, but the same functionality can be achieved using the following methods:

  1. standard string stream
#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    std::stringstream ss;
    int num = 123;
    double pi = 3.14159;

    ss << "The number is: " << num << ", and the value of pi is: " << std::fixed << std::setprecision(2) << pi;
    std::cout << ss.str() << std::endl;

    return 0;
}
  1. print out
#include <iostream>

int main() {
    int num = 123;
    double pi = 3.14159;

    printf("The number is: %d, and the value of pi is: %.2f\n", num, pi);

    return 0;
}

These methods allow for formatting output of data, providing a certain level of flexibility and control.

bannerAds