printf() 如何实现可变字段宽度? [英] How can variable field width be implemented with printf()?

查看:52
本文介绍了printf() 如何实现可变字段宽度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是:

如何使用printf() 实现可变字段宽度?也就是说,应该在运行时指定宽度,而不是 %8d.

How can variable field width be implemented using printf()? That is, instead of %8d, the width should be specified at run time.

基于上述问题,我在 Internet 上遇到了一些 C 代码,但由于我是 C 编程的新手,我无法对代码进行正面或反面处理.我在下面发布代码:

I came across some C code on the Internet based on the question above but as I am new to C programming I haven't been able to make heads or tails of the code. I am posting the code below:

#include <stdio.h>

int main()
{
   const char text[] = "Hello world";
   int i;
   for ( i = 1; i < 12; ++i )
   {
      printf("\"%.*s\"\n", i, text);
   }


    return 0;
}

推荐答案

首先,让我告诉你,你展示的代码是关于控制精度,而不是字段宽度.对于缩短表单**

First of all, let me tell you, the code you have shown is about controlling the precision, not the field width. For a shortened form**

 %A.B<format specifier>

A 表示字段宽度,B 表示精度.

A denotes the field width and B makes the precision.

现在,引用 C11 标准,第 7.21.6.1 章,fprintf()(强调我的)

Now, quoting the C11 standard, chapter §7.21.6.1, fprintf() (emphasis mine)

每个转换规范都由字符 % 引入.在 % 之后,以下依次出现:

Each conversion specification is introduced by the character %. After the %, the following appear in sequence:

[..]

  • 一个可选精度,它给出了 dii 出现的最少位数,ouxX 转换,小数点后出现的位数aAeEf 的字符>F 转换,最大有效次数gG 转换的数字,或 s 转换写入的最大字节数.精度采用句点 (.) 后跟的形式星号 *(稍后描述)或可选的十进制整数;如果只有期间是指定时,精度为零.如果精度与任何其他转换说明符,行为未定义.
  • An optional precision that gives the minimum number of digits to appear for the d, i, o, u, x, and X conversions, the number of digits to appear after the decimal-point character for a, A, e, E, f, and F conversions, the maximum number of significant digits for the g and G conversions, or the maximum number of bytes to be written for s conversions. The precision takes the form of a period (.) followed either by an asterisk * (described later) or by an optional decimal integer; if only the period is specified, the precision is taken as zero. If a precision appears with any other conversion specifier, the behavior is undefined.

如上所述,字段宽度或精度或两者都可以用星号表示.在在这种情况下,int 参数提供字段宽度或精度.[...]

As noted above, a field width, or precision, or both, may be indicated by an asterisk. In this case, an int argument supplies the field width or precision. [...]

所以,就你而言,

printf("\"%.*s\"\n", i, text);

精度将由 i 提供,它可以在运行时保存不同的值.

the precision will be supplied by i which can hold different values at run-time.

完整的格式(为了便于阅读,分成不同的行)

%
<Zero or more flags>
<optional minimum field width>
<optional precision>
<optional length modifier>
<A conversion specifier character>

这篇关于printf() 如何实现可变字段宽度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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