gpt4 book ai didi

c - 如何使用 printf() 实现可变字段宽度?

转载 作者:行者123 更新时间:2023-11-30 16:11:22 25 4
gpt4 key购买 nike

问题是:

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

基于上述问题,我在互联网上发现了一些 C 代码,但由于我是 C 编程新手,所以我无法弄清楚这些代码。我发布以下代码:

#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;
}

最佳答案

首先,让我告诉你,你所显示的代码是关于控制精度的,而不是字段宽度。对于缩写形式**

 %A.B<format specifier>

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

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

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

[..]

  • 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.

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提供,它可以在运行时保存不同的值。

<小时/>

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

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

关于c - 如何使用 printf() 实现可变字段宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58635285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com