Format Text with the New Format Library
Explore the C++20 format library introduced in the <format> header, which combines type safety and performance for text formatting. Understand how it replaces legacy printf and iostream methods with a Python-like syntax. Learn to format strings and customize output for user-defined types to write clearer, safer, and more efficient code.
We'll cover the following...
Until now, if we wanted to format text, we could use either the legacy printf functions or the STL iostream library. Both have their strengths and flaws.
The printf based functions are inherited from C and have proven efficient, flexible, and convenient for over 50 years. The formatting syntax can look a bit cryptic, but it's simple enough once we get used to it.
printf("Hello, %s\n", c_string);
The main weakness in printf is its lack of type safety. The common printf() function (and its relatives) use
The STL iostream the library brings type safety at the expense of readability and run-time performance. The iostream syntax is unusual, yet familiar. It overloads the bitwise left-shift operator (<<) to allow a chain of objects, operands, and formatting manipulators, which produce the formatted output.
cout << "Hello, " << str << endl;
The weakness of iostream is its complexity, in both syntax and ...