#define SIZE 9
int number=5;
char letters[SIZE]; /* this wont be null-terminated */
...
char fmt_string[20];
sprintf(fmt_string, "%%d %%%ds", SIZE);
/* fmt_string = "%d %9d"... or it should be */
printf(fmt_string, number, letters);
Is there a better way to do this?
There is no need to construct a special format string.
printfallows you to specify the precision using a parameter (that precedes the value) if you use a.*as the precision in the format tag.For example:
Note: there is a distinction between width (which is a minimum field width) and precision (which gives the maximum number of characters to be printed).
%*sspecifies the width,%.sspecifies the precision. (and you can also use%*.*but then you need two parameters, one for the width one for the precision)See also the printf man page (
man 3 printfunder Linux) and especially the sections on field width and precision: