本文介绍了关于 C 中的 printf 格式字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们来看看下面的程序:

Let's take the following program:

#include <stdio.h>

int main()
{
    long t =57 ;
    printf("[%+03ld]", t);
}

它的输出:

[+57]

我有点困惑:我告诉他用零填充输出到宽度 3 (03ld),但是似乎如果我强制输出在数字前放一个加号(+) 如果数字的长度已经是 2 位数字(如 57),则不会添加所需的零.对于小于 10 的数字,用 1 个零填充.

I am somehow confused: I told him to pad the output to width 3 (03ld), with zeroes, however it seems that if I force the output to put a plus sign before the number (+) it will not add the required zeroes if the length of the number is already 2 digits (as in 57). For numbers <10 it pads with 1 zero.

来自 http://www.cplusplus.com/reference/cstdio/printf/

(0) ->指定填充时,用零 (0) 而不是空格左填充数字(请参阅宽度子说明符).

(+) ->即使对于正数,也强制在结果前面加上加号或减号(+ 或 -).默认情况下,只有负数前面带有 - 符号.

(+) -> Forces to preceed the result with a plus or minus sign (+ or -) even for positive numbers. By default, only negative numbers are preceded with a - sign.

(宽度)->要打印的最少字符数.如果要打印的值比这个数字短,则结果用空格填充.即使结果更大,该值也不会被截断.

(width) -> Minimum number of characters to be printed. If the value to be printed is shorter than this number, the result is padded with blank spaces. The value is not truncated even if the result is larger.

所以我只需要澄清一下……上面引用中的 (width) 说明符指的是由 this 控制的输出字符串的全长(即:将要打印的字符)格式说明符 ("%+03ld") 或要打印的数字字符的全长?

So I just need a clarification ... The (width) specifier from the quote above refers to the full length of the output string (ie: the characters that will be printed) controlled by this format specifier ("%+03ld") or the full length of the characters of the number that is going to be printed?

推荐答案

是的,宽度说明符是指整个格式化结果的宽度,在您的情况下为 +57.这使得它可用于打印柱状文本以便在屏幕上轻松阅读(如果您使用 C 编写老式文本实用程序,这一点很重要!).

Yes, the width specifier refers to the width of the entire formatted result, +57 in your case. This makes it useful for printing columnar text for easy reading on screen (important if you're using C to write an old-school text utility!).

这篇关于关于 C 中的 printf 格式字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 09:14