In formatting functions like std::format, replacement fields can add format specifications as a list of options. For example,
std::format("{:*>5}", d);
will display d
aligned to the right with a padding of '*' to its left so that the display is
always at least five characters wide.
Some of these options work together, and mentioning one without the other can lead to confusing code where it is unclear to the reader how the
output will look. The same can happen if the options have incompatible values.
This rule raises an issue when:
- The alignment or the padding options are set, but the width option is not specified, leading to no actual padding.
- Both a character padding and a 0 padding are specified on a numerical value, leading to the 0 padding being ignored.
Noncompliant code example
void print() {
// Noncompliant, filling with no width has no effect
std::cout << std::format("{:*>}\n", "filled");
// Noncompliant, filling with both * and 0 result in 0 being ignored
std::cout << std::format("{:*>05}\n", 12);
// Noncompliant, padding with 0 when no width is specified does nothing
std::cout << std::format("{:0}\n", 12);
}
Compliant solution
void print() {
std::cout << std::format("{:*>10}\n", "filled");
std::cout << std::format("{:*>5}\n", 12);
std::cout << std::format("{:04}\n", 12);
}