Skip to content

Commit

Permalink
fix interaction of space flag and '+' flag, as well as '-' flag and '…
Browse files Browse the repository at this point in the history
…0' flag (#1687)
  • Loading branch information
rimathia authored May 17, 2020
1 parent eee2023 commit 6b219a5
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
9 changes: 6 additions & 3 deletions include/fmt/printf.h
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,9 @@ void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs,
specs.fill[0] = '0';
break;
case ' ':
specs.sign = sign::space;
if (specs.sign != sign::plus) {
specs.sign = sign::space;
}
break;
case '#':
specs.alt = true;
Expand Down Expand Up @@ -517,10 +519,11 @@ OutputIt basic_printf_context<OutputIt, Char>::format() {
if (specs.alt && visit_format_arg(detail::is_zero_int(), arg))
specs.alt = false;
if (specs.fill[0] == '0') {
if (arg.is_arithmetic())
if (arg.is_arithmetic() && specs.align != align::left)
specs.align = align::numeric;
else
specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types.
specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-'
// flag is also present.
}

// Parse length and convert the argument to the required type.
Expand Down
23 changes: 23 additions & 0 deletions test/printf-test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,18 @@ TEST(PrintfTest, PlusFlag) {

// '+' flag is ignored for non-numeric types.
EXPECT_PRINTF("x", "%+c", 'x');

// '+' flag wins over space flag
EXPECT_PRINTF("+42", "%+ d", 42);
EXPECT_PRINTF("-42", "%+ d", -42);
EXPECT_PRINTF("+42", "% +d", 42);
EXPECT_PRINTF("-42", "% +d", -42);
EXPECT_PRINTF("+0042", "% +05d", 42);
EXPECT_PRINTF("+0042", "%0+ 5d", 42);

// '+' flag and space flag are both ignored for non-numeric types.
EXPECT_PRINTF("x", "%+ c", 'x');
EXPECT_PRINTF("x", "% +c", 'x');
}

TEST(PrintfTest, MinusFlag) {
Expand All @@ -160,6 +172,17 @@ TEST(PrintfTest, MinusFlag) {
EXPECT_PRINTF("7 ", "%-5d", 7);
EXPECT_PRINTF("97 ", "%-5hhi", 'a');
EXPECT_PRINTF("a ", "%-5c", 'a');

// '0' flag is ignored if '-' flag is given
EXPECT_PRINTF("7 ", "%-05d", 7);
EXPECT_PRINTF("7 ", "%0-5d", 7);
EXPECT_PRINTF("a ", "%-05c", 'a');
EXPECT_PRINTF("a ", "%0-5c", 'a');
EXPECT_PRINTF("97 ", "%-05hhi", 'a');
EXPECT_PRINTF("97 ", "%0-5hhi", 'a');

// '-' and space flag don't interfere
EXPECT_PRINTF(" 42", "%- d", 42);
}

TEST(PrintfTest, SpaceFlag) {
Expand Down

0 comments on commit 6b219a5

Please sign in to comment.