C++ compiler support (access 26.03.2021)
https://en.cppreference.com/w/cpp/compiler_support

String formatting in c++
In 2021 formatting string in C++ (unless you are using some 3rd party library like boost::format) involves using pritnf() functions, that are inherited from C (so quite old), or use stringstream which is maybe not as efficient as we would expect specially if you want to format floating point numbers, and it produces twice as much code as printf().
std::format syntax
cout << format("┌{0:─^{2}}┐\n"
"│{1: ^{2}}│\n"
"└{0:─^{2}}┘\n",
"", "Hello, world!", 20);
┌────────────────────┐
│ Hello, world! │
└────────────────────┘
Ok, so maybe let start with something simpler. General syntax is “inspired” by string formatting in other languages 🙂 like python:
cout << format("Decimals: {} {}\n", 1977, 650000L);
Syntax supports indexed and named arguments:
cout << format("named arguments: {name}, {surename}",
arg("name", "my name"), arg("surename", "my familly name")) << endl;
cout << format("indexed arguments {0}, {1}, {0}", "zero", "first")
<< std::endl;
It formats std::chrono straight out of the box:
cout << format("date formatting: {:%Y-%m-%d}", localtime(time(nullptr))) << endl;
Paddings, aligments and other stuff:
cout << format("Decimal whithin space of 10 characters: {:10} {} \n", 1977,
650000L);
cout << format(
"Decimal whithin space of 10 characters aligned left: {:<10}.\n", 1977);
cout << format("Decimal whithin space of 10 characters aligned right, "
"preceding zeros: {:0>10}.\n",
1977);
cout << format("Decimal whithin space of 10 characters aligned center, "
"surrounded *: {:*^10}.\n",
1977);
cout << format("Float: {} .\n", -0.0000199999f);
cout << format("Float with 5 digit precision: {:.5f} .\n", -0.0000199999f);
cout << format("Padded hex {:#04x} \n", 0);
And all of this stays no not implemented 🙂
Check the {fmt} library which implementation is std::format compatible.
{fmt} is in fact a great library, not only because of that compatibility, it is real improvement in thee area of string formatting in C++. It outperforms both printf and stringstream. Produces really nice and compact executable code. The library is fully type safe, errors in format strings can be reported at compile time, automatic memory management prevents buffer overflow errors.
Footnote:
I do not really want to repeat {fmt} webpage, but I really want to recommend using this library, specially that moving to std::format will be an easy peasy task.
For compilable code please check my github.
Special thanks for Mateusz Janek for showing me {fmt} and for contribution 🙂
With all of the {fmt} goodness 🙂
Michal