C语言 在 printf 中设置可变文本列宽

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7105890/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 09:25:27  来源:igfitidea点击:

Set variable text column width in printf

csizeprintf

提问by Alaa M.

In order to determine the size of the column in C language we use %<number>d. For instance, I can type %3dand it will give me a column of width=3. My problem is that my number after the %is a variable that I receive, so I need something like %xd(where xis the integer variable I received sometime before in my program). But it's not working.

为了确定 C 语言中列的大小,我们使用%<number>d. 例如,我可以打字%3d,它会给我一列宽度=3。我的问题是%我收到的数字是一个变量,所以我需要类似的东西%xdx我之前在程序中收到的整数变量在哪里)。但它不起作用。

Is there any other way to do this?

有没有其他方法可以做到这一点?

回答by Oliver Charlesworth

You can do this as follows:

您可以按如下方式执行此操作:

printf("%*d", width, value);

From Lee's comment:
You can also use a * for the precision size:

来自 Lee 的评论:
您还可以使用 * 作为精确尺寸:

printf("%*.*f", width, precision, value);

回答by jetset

Just for completeness, wanted to mention that with POSIX-compliant versions of printf()you can also put the actual field width (or precision) value somewhere else in the parameter list and refer to it using the 1-based parameter number followed by a dollar sign:

只是为了完整性,想提一下,使用 POSIX 兼容版本,printf()您还可以将实际字段宽度(或精度)值放在参数列表中的其他位置,并使用基于 1 的参数编号后跟美元符号来引用它:

A field width or precision, or both, may be indicated by an asterisk ‘?' or an asterisk followed by one or more decimal digits and a ‘$' instead of a digit string. In this case, an int argument supplies the field width or precision. A negative field width is treated as a left adjustment flag followed by a positive field width; a negative precision is treated as though it were missing. If a single format directive mixes positional (nn$) and non-positional arguments, the results are undefined.

字段宽度或精度,或两者,可以用星号“?”表示。或星号后跟一个或多个十进制数字和一个“$”而不是数字字符串。在这种情况下, int 参数提供字段宽度或精度。负场宽被视为左调整标志,然后是正场宽;负精度被视为缺失。如果单个格式指令混合了位置 (nn$) 和非位置参数,则结果未定义。

E.g., printf ( "%1$*d", width, value );

例如, printf ( "%1$*d", width, value );