Skip to content

Commit be30479

Browse files
committed
fix(printf): fix trailing field width in itoa conversion
Fixes #21
1 parent e6b5331 commit be30479

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

printf.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,8 @@ static inline unsigned int _atoi(const char** str)
151151
// internal itoa format
152152
static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t maxlen, char* buf, size_t len, bool negative, unsigned int base, unsigned int prec, unsigned int width, unsigned int flags)
153153
{
154+
const size_t start_idx = idx;
155+
154156
// pad leading zeros
155157
while (!(flags & FLAGS_LEFT) && (len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
156158
buf[len++] = '0';
@@ -208,7 +210,7 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
208210

209211
// append pad spaces up to given width
210212
if (flags & FLAGS_LEFT) {
211-
while (idx < width) {
213+
while (idx - start_idx < width) {
212214
out(' ', buffer, idx++, maxlen);
213215
}
214216
}

test/test_suite.cpp

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -582,6 +582,18 @@ TEST_CASE("width -20", "[]" ) {
582582

583583
test::sprintf(buffer, "%-20c", 'x');
584584
REQUIRE(!strcmp(buffer, "x "));
585+
586+
test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 9, 9, 9);
587+
REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));
588+
589+
test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 10, 10, 10);
590+
REQUIRE(!strcmp(buffer, "| 10| |10| | 10|"));
591+
592+
test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 9, 9, 9);
593+
REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));
594+
595+
test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 10, 10, 10);
596+
REQUIRE(!strcmp(buffer, "| 10| |10 | | 10|"));
585597
}
586598

587599

0 commit comments

Comments
 (0)