diff --git a/include/fmt/printf.h b/include/fmt/printf.h index 71c0e274..a1c4b403 100644 --- a/include/fmt/printf.h +++ b/include/fmt/printf.h @@ -257,6 +257,7 @@ class printf_arg_formatter : public detail::arg_formatter_base { return (*this)(static_cast(value)); fmt_specs.sign = sign::none; fmt_specs.alt = false; + fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types. // align::numeric needs to be overwritten here since the '0' flag is // ignored for non-numeric types if (fmt_specs.align == align::none || fmt_specs.align == align::numeric) @@ -508,6 +509,10 @@ OutputIt basic_printf_context::format() { } format_arg arg = get_arg(arg_index); + // For d, i, o, u, x, and X conversion specifiers, if a precision is + // specified, the '0' flag is ignored + if (specs.precision >= 0 && arg.is_integral()) + specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-' present. if (specs.precision >= 0 && arg.type() == detail::type::cstring_type) { auto str = visit_format_arg(detail::get_cstring(), arg); auto str_end = str + specs.precision; diff --git a/test/printf-test.cc b/test/printf-test.cc index 9dd5bdd5..da980e80 100644 --- a/test/printf-test.cc +++ b/test/printf-test.cc @@ -139,8 +139,11 @@ TEST(PrintfTest, ZeroFlag) { EXPECT_PRINTF("+00042", "%00+6d", 42); + EXPECT_PRINTF(" 42", "%05.d", 42); + EXPECT_PRINTF(" 0042", "%05.4d", 42); + // '0' flag is ignored for non-numeric types. - EXPECT_PRINTF("0000x", "%05c", 'x'); + EXPECT_PRINTF(" x", "%05c", 'x'); } TEST(PrintfTest, PlusFlag) {