...

/

Format Text with the New Format Library

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 C's variadic arguments model C's variadic arguments model allows a function to accept a variable number of arguments of different types. to pass parameters to a formatter. This works great when it works, but it can cause serious problems when a parameter type doesn't match its corresponding format specifier. Modern compilers do as much type-checking as they can, but the model is inherently flawed, and the protection can only go so far.

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 ...