- 4.1 Introduction
- 4.2 Essentials of Counter-Controlled Iteration
- 4.3 for Iteration Statement
- 4.4 Examples Using the for Statement
- 4.5 Application: Summing Even Integers
- 4.6 Application: Compound-Interest Calculations
- 4.7 do... while Iteration Statement
- 4.8 switch Multiple-Selection Statement
- 4.9 C++17 Selection Statements with Initializers
- 4.10 break and continue Statements
- 4.11 Logical Operators
- 4.12 Confusing the Equality (==) and Assignment (=) Operators
- 4.13 Objects-Natural Case Study: Using the miniz-cpp Library to Write and Read ZIP files
- 4.14 C++20 Text Formatting with Field Widths and Precisions
- 4.15 Wrap-Up
20 4.14 C++20 Text Formatting with Field Widths and Precisions
Section 3.13 introduced C++20’s format function (in header <format>), which provides powerful new text-formatting capabilities. Figure 4.12 shows how format strings can concisely specify what each value’s format should be. We reimplement the formatting introduced in Fig. 4.4’s compound-interest problem. Figure 4.12 produces the same output as Fig. 4.4, so we’ll focus exclusively on the format strings in lines 13, 14, 17 and 22.
1 // fig04_12.cpp 2 // Compound-interest example with C++20 text formatting. 3 #include <iostream> 4 #include <cmath> // for pow function 5 #include <fmt/format.h> // in C++20, this will be #include <format> 6 using namespace std; 7 using namespace fmt; // not needed in C++20 8 9 int main() { 10 double principal{1000.00}; // initial amount before interest 11 double rate{0.05}; // interest rate 12 13 cout << format("Initial principal: {:>7.2f}\n", principal) 14 << format(" Interest rate: {:>7.2f}\n", rate); 15 16 // display headers 17 cout << format("\n{}{:>20}\n", "Year", "Amount on deposit"); 18 19 // calculate amount on deposit for each of ten years 20 for (int year{1}; year <= 10; ++year) { 21 double amount = principal * pow(1.0 + rate, year); 22 cout << format("{:>4d}{:>20.2f}\n", year, amount); 23 } 24 }
Initial principal: 1000.00 Interest rate: 0.05 Year Amount on deposit 1 1050.00 2 1102.50 3 1157.63 4 1215.51 5 1276.28 6 1340.10 7 1407.10 8 1477.46 9 1551.33 10 1628.89
Fig. 4.12 Compound-interest example with C++20 string formatting.
Formatting the Principal and Interest Rate
The format calls in lines 13 and 14 each use the placeholder {:>7.2f} to format the values of principal and rate. A colon (:) in a placeholder introduces a format specifier that indicates how a corresponding value should be formatted. The format specifier >7.2f is for a floating-point number (f) that should be right-aligned (>) in a 7-character field width that has two digits of precision (.2) to the right of the decimal point. Unlike setprecision and fixed shown earlier, format settings specified in placeholders are not “sticky”—they apply only to the value that’s inserted into that placeholder.
The value of principal (1000.00) requires exactly seven characters to display, so no spaces are required to fill out the field width. The value of rate (0.05) requires only four total character positions, so it will be right-aligned in the field of seven characters and filled from the left with leading spaces, as in
Numeric values are right-aligned by default, so the > is not required here. You can left-align numeric values in a field width via <.
Formatting the Year and Amount-on-Deposit Column Heads
In line 17’s format string
"\n{}{:>20}\n"
the string "Year" is simply placed at the position of the first placeholder, which does not contain a format specifier. The second placeholder indicates that "Amount on Deposit" (17 characters) should be right-aligned (>) in a field of 20 characters—format inserts three leading spaces to right-align the string. Strings are left-aligned by default, so the > is required here to force right-alignment.
Formatting the Year and Amount-on-Deposit Values in the for Loop
The format string in line 22
"{:>4d}{:>20.2f}\n"
uses two placeholders to format the loop’s output. The placeholder {:>4d} indicates that year’s value should be formatted as an integer (d means decimal integer) right-aligned (>) in a field of width 4. This right-aligns all the year values under the "Year" column.
The placeholder {:>20.2f} formats amount’s value as a floating-point number (f) right-aligned (>) in a field width of 20 with a decimal point and two digits to the right of the decimal point (.2). Formatting the amounts this way aligns their decimal points vertically, as is typical with monetary amounts. The field width of 20 right-aligns the amounts under "Amount on Deposit".