printf string, variable length item

CFormatPrintf

C Problem Overview


#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?

C Solutions


Solution 1 - C

There is no need to construct a special format string. printf allows 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:

printf ("%d %.*s", number, SIZE, letters);

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). %*s specifies the width, %.s specifies 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 printf under Linux) and especially the sections on field width and precision:

> Instead of a decimal digit string one may write "*" or "*m$" (for some > decimal integer m) to specify that the precision is given in the next > argument, or in the m-th argument, respectively, which must be of type int.

Solution 2 - C

A somewhat unknown function is asprintf. The first parameter is a **char. This function will malloc space for the string so you don't have to do the bookkeeping. Remember to free the string when done.

char *fmt_string;

asprintf(&fmt_string, "%%d %%%ds", SIZE);
printf(fmt_string, number, letters);
free(fmt_string);

is an example of use.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionWilliam EntrikenView Question on Stackoverflow
Solution 1 - CTrentView Answer on Stackoverflow
Solution 2 - CNo One in ParticularView Answer on Stackoverflow