printf 字符串,可变长度项 [英] printf string, variable length item
问题描述
#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?
推荐答案
不需要构造特殊格式的字符串.如果您使用 .*
作为格式标记中的精度,printf
允许您使用参数(在值之前)指定精度.
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.
例如:
printf ("%d %.*s", number, SIZE, letters);
注意:宽度(即最小字段宽度)和精度(给出要打印的最大字符数)之间存在区别.%*s
指定宽度,%.s
指定精度.(你也可以使用 %*.*
但是你需要两个参数,一个用于宽度,一个用于精度)
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)
另见 printf 手册页 (man 3 printf
在 Linux 下),尤其是关于字段宽度和精度的部分:
See also the printf man page (man 3 printf
under Linux) and especially the sections on field width and precision:
可以写成*"或*m$"而不是十进制数字字符串(对于某些十进制整数 m) 指定精度在下一个给出参数,或分别在第 m 个参数中,它必须是 int 类型.
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.
这篇关于printf 字符串,可变长度项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!