How to right pad with zeros using sprintf?

I need to right-pad with zeros a string by using (s)printf.

I looked up the manual and tried with

printf("%-19s", buffer);

which right-pad the string with spaces. So I tried

printf("%019s", buffer);

which left-pad the string with zeros. So I tried both

printf("%-019s", buffer);
printf("%0-19s", buffer);

but I still got a right-pad string with spaces.

I need a right-pad string with zeros. :slight_smile:

Can I have that result with (s)printf() ?

Thanks in advance,
S.

$ echo "buffer" | ruby -e 'puts gets.chomp.ljust(20,"0")'
buffer00000000000000

Did I forget to specify that I need to do this in C(++)?

nowhere in your post states C++. and most other languages support printf and sprintf functions.

You are right. I fixed the title. Thanks.

The stdC library doesn't specify that. Start with this C code and C++ -ify it.

char *rpad(char *dest, const char *src, const char pad, const size_t sz)
{
   memset(dest, pad, sz);
   dest[sz]=0x0;
   memcpy(dest, src, strlen(src));
   return dest;
}
printf("%s%019s\n", buffer, "0");

shamrock - good idea - that will work with generalization = * as a complete solution


printf("%s%0*s\n", buffer,strlen(buffer)-20,  "0");

Note: this is not complete - it has to handle overflow -- where the length of buffer > 20 (or whatever size)

I'm not sure I understood how it works.

The first character conversion prints whatever the buffer variable contains.
The second should print "0" padded with 18 zeros right?

Wouldn't that produce an output as big as strlen(buffer) + 19?

It would be right padded with 19 zeros.

So you need to right pad zeros all the empty slots of buffer...and did you look at all at the solution posted by jim mcnanamara. It has exactly what you want...

s = sizeof buf;
l = strlen(buf);
d = s - l;
printf("%s%0*s\n", buf, d>0 ? d : 0, d>0 ? "0" : "");