aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMarco Paland <marco@paland.com>2018-08-21 13:13:13 +0200
committerMarco Paland <marco@paland.com>2018-08-21 13:13:13 +0200
commitbe3047911075b2e917d73451068e0b84373eefb9 (patch)
tree1ea834a5fdc1daeea15a4ea0d8aec22da2113b49
parente6b5331a36a5815cc36a9b2872f29234efee72cb (diff)
downloadprintf-be3047911075b2e917d73451068e0b84373eefb9.tar.gz
printf-be3047911075b2e917d73451068e0b84373eefb9.tar.bz2
printf-be3047911075b2e917d73451068e0b84373eefb9.zip
fix(printf): fix trailing field width in itoa conversion
Fixes #21
-rw-r--r--printf.c4
-rw-r--r--test/test_suite.cpp12
2 files changed, 15 insertions, 1 deletions
diff --git a/printf.c b/printf.c
index c28cf13..e4c83e5 100644
--- a/printf.c
+++ b/printf.c
@@ -151,6 +151,8 @@ static inline unsigned int _atoi(const char** str)
// internal itoa format
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)
{
+ const size_t start_idx = idx;
+
// pad leading zeros
while (!(flags & FLAGS_LEFT) && (len < prec) && (len < PRINTF_NTOA_BUFFER_SIZE)) {
buf[len++] = '0';
@@ -208,7 +210,7 @@ static size_t _ntoa_format(out_fct_type out, char* buffer, size_t idx, size_t ma
// append pad spaces up to given width
if (flags & FLAGS_LEFT) {
- while (idx < width) {
+ while (idx - start_idx < width) {
out(' ', buffer, idx++, maxlen);
}
}
diff --git a/test/test_suite.cpp b/test/test_suite.cpp
index 212fbd3..3ecac5f 100644
--- a/test/test_suite.cpp
+++ b/test/test_suite.cpp
@@ -582,6 +582,18 @@ TEST_CASE("width -20", "[]" ) {
test::sprintf(buffer, "%-20c", 'x');
REQUIRE(!strcmp(buffer, "x "));
+
+ test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 9, 9, 9);
+ REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));
+
+ test::sprintf(buffer, "|%5d| |%-2d| |%5d|", 10, 10, 10);
+ REQUIRE(!strcmp(buffer, "| 10| |10| | 10|"));
+
+ test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 9, 9, 9);
+ REQUIRE(!strcmp(buffer, "| 9| |9 | | 9|"));
+
+ test::sprintf(buffer, "|%5d| |%-12d| |%5d|", 10, 10, 10);
+ REQUIRE(!strcmp(buffer, "| 10| |10 | | 10|"));
}