printf的字符串,长度可变项 [英] printf string, variable length item

查看:941
本文介绍了printf的字符串,长度可变项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 允许您使用一个参数(即precedes值),如果使用指定precision一个。* 作为格式标签precision。

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);

请注意:有和宽度之间的区别(这是一个最小字段宽度)precision(可提供的最大字符数要打印)。
%* S 指定宽度%:S 指定precision。 (你也可以使用%*。* 但随后你需要两个参数,一个是宽度一为precision)

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的手册页( 3人的printf Linux下),尤其是现场的宽度和precision的部分:

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 field width is given in the next argument, or in the m-th argument, respectively, which must be of type int. [...]

而不是十进制数字字符串的人们可以写的*或* M $(对于某些
  十进制整数M)来指定precision将在未来给
  参数,或者在第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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆