Why is this an issue?
std::format
and the related formatting functions provide two different options to pad numerical values up to a specific width:
- The usual character padding that applies to many types and looks like:
std::format(“{:*>5}”, num);
. This adds as many '*'
characters as necessary to reach a width of 5.
- Adding the number 0 just before the width to declare numeric padding:
std::format(“{:05}”, num);
. This numeric padding adds 0
before the number and therefore takes no alignment option.
When working with numeric values, one almost always wants to use the numeric padding as it works correctly with signed numbers:
std::format("{:0>5}", -10); // Usual padding, prints 00-10
std::format("{:05}", -10); // Numeric padding, -0010
This rule raises an issue when a format specification uses '0' as a padding character instead of using numeric padding.
Noncompliant code example
void formatted(int i, double d) {
std::cout << std::format("{:0>5}\n", i); // Noncompliant
std::cout << std::format("{:0>#5}\n", d); // Noncompliant
}
Compliant solution
void formatted(int i, double d) {
std::cout << std::format("{:05}\n", i); // Compliant
std::cout << std::format("{:#05}\n", d); // Compliant
}