First, let me state that I'm a real newb to C so I apologize in advance if I'm asking dumb questions..
I'm trying to create a padding function for padding numbers with 0's to specified width and I found that one of the formats specified by printf is a * to indicate that the first parameter is actually the length of the padding however this does not work in practice as it always returns a 0 length string when I try to use it. So, my first question is, does anyone know why? ex: sprintf(buf, "%*d", 3, 7) should return "007" but returns "" instead.
I tried to come up with my own method of accomplishing this but my lack of C knowledge caused me to come up with what seems to me like a very lacking solution:
char * pad( int number, char width ) {
static char buf[6];
char params[5];
params[0] = '%';
params[1] = '0';
params[2] = width;
params[3] = 'd';
params[4] = '\0';
sprintf(buf, params, number);
return buf;
}
I assume there must be a better way of doing this? The first issue is that I shouldn't have to pass the width as a char, but I could not find a way to convert a byte to a char, at least not a short hand method that would work without adding more lines of code. I'm also limited to only padding up to 9 chars which I will never need more of but it drives me nuts that I've coded in a limitation.
Any help with his is HUGELY appreciated!!