Format Text with the New Format Library
Learn to format text with the new format library.
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 implementation. Building a formatted string can be verbose and obscure. Many of the formatting manipulators must be reset after use, or they create cascading formatting errors that can be difficult to debug. The library itself is vast and complex, resulting in code significantly larger and slower ...