I have a dummy question. I would like to print an integer into a buffer padding with 0 but I cannot sort it out the sprintfformat.
I am trying the following
It's %030d, with type-letter at the end.
A fairly effective version that doesn't need any slow library calls:
#include <stdio.h>
void uint_tostr (unsigned int n, size_t buf_size, char dst[buf_size])
{
const size_t str_size = buf_size-1;
for(size_t i=0; i<str_size; i++)
{
size_t index = str_size - i - 1;
dst[index] = n%10 + '0';
n/=10;
}
dst[str_size] = '\0';
}
int main (void)
{
unsigned int n = 1234;
char str[6+1];
uint_tostr(n, 6+1, str);
puts(str);
}
This can be optimized further, though it is still probably some hundred times faster than sprintf as is.
The padding and width come before the type specifier:
sprintf( buf, "%030d", my_val );
Your precision and width parameters need to go between the '%' and the conversion specifier 'd', not after. In fact all flags do. So if you want a preceeding '+' for positive numbers, use '%+d'.
"%030d" is the droid you are looking for
Try:
sprintf( buf, "%030d", my_val );