C语言 printf 字符串,可变长度项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5932214/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
printf string, variable length item
提问by William Entriken
#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?
有一个更好的方法吗?
回答by Trent
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.
不需要构造特殊的格式字符串。 printf如果您.*在格式标记中使用 a作为精度,则允许您使用参数(在值之前)指定精度。
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).
%*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)
注意:宽度(最小字段宽度)和精度(给出要打印的最大字符数)之间存在区别。
%*s指定宽度,%.s指定精度。(你也可以使用,%*.*但是你需要两个参数,一个是宽度,一个是精度)
See also the printf man page (man 3 printfunder Linux) and especially the sections on field width and precision:
另请参阅 printf 手册页(man 3 printf在 Linux 下),尤其是有关字段宽度和精度的部分:
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.
代替十进制数字字符串,可以写“*”或“*m$”(对于某些十进制整数 m)来指定精度分别在下一个参数或第 m 个参数中给出,它们必须是类型为 int。
回答by No One in Particular
A somewhat unknown function is asprintf. The first parameter is a **char. This function will mallocspace for the string so you don't have to do the bookkeeping. Remember to freethe string when done.
一个有点未知的函数是asprintf。第一个参数是**char. 此函数将为malloc字符串留出空间,因此您不必进行簿记。完成后请记住free字符串。
char *fmt_string;
asprintf(&fmt_string, "%%d %%%ds", SIZE);
printf(fmt_string, number, letters);
free(fmt_string);
is an example of use.
是一个使用示例。

