我的问题很简单。我想使用printf打印指定数量的前导零整数。但是,前导零的数量是在运行时决定的,而不是预先知道的。我该怎么做?
如果我知道字符数(比如说5个),那么可以这样做:
如果我知道字符数(比如说5个),那么可以这样做:
printf("%05d", number);
但我不知道它是否会是5。
您可以使用*
来传递宽度:
printf("%0*d", 5, number);
cout << setw(width_) << setfill('0') << integerVariable_;
其中width_
是在运行时确定的。
printf
系列中使用printf("%.*d", precision, number)
;precision格式化字段指定要显示的最小数字位数,预设值为1。这与宽度无关,因此可以编写以下内容:printf("%6.3d", 12); // outputs " 012"
printf("%6.0d", 0); // outputs " ", without any 0
对于宽度或精度(或两者),您可以指定'*'
,这将导致printf
从参数中获取值(传递一个int
):
printf("%6.*d", 3, 12); // outputs " 012"
printf("%*.3d", 6, 12); // outputs " 012"
printf("%*.*d", 6, 3, 12); // outputs " 012"
很遗憾,在ostream
中没有相应的功能:在输出整数时,精度会被忽略。(这可能是因为精度没有类型相关的默认值。默认值是6,适用于所有尊重它的类型。)
int width = whatever();
printf("%0*d", width, number );
printf
系列)。遗憾的是,在iostream中不支持它——精度字段在整数输出中被忽略。 - James Kanze使用C++中提供的操纵符setw和setfill。
'.'
开头,例如printf("%.*d", 5, number)
。 - James Kanze