简体   繁体   中英

Parameterized Leading Zeros in C++ printf function

my question is simple. I want to print integers with a specified amount of leading zeros, using printf. However, the number of leading zeros is decided runtime, not known a priori. How could I do that?

If I knew the number of characters (let's say 5), it would be

printf("%05d", number);

But I don't know if it will be 5.

您可以使用*传递宽度:

printf("%0*d", 5, number);

You can also use

cout << setw(width_) << setfill('0') << integerVariable_;

where width_ is decided at runtime.

I belive the asterisk can be used to achieve this on most platforms.

int width = whatever();
printf("%0*d", width, number );

The standard solution here would be printf("%.*d", precision, number) ; in the printf family, in C, the precision formatting field specifies a minimum number of digits to be displayed, defaulting to 1. This is independent of the width, so you can write things like:

printf("%6.3d", 12);    // outputs "   012"
printf("%6.0d",  0);    // outputs "      ", without any 0

For either the width or the precision (or both), you can specify '*' , which will cause printf to pick the value up from an argument (pass an int ):

printf("%6.*d", 3, 12); // outputs "   012"
printf("%*.3d", 6, 12); // outputs "   012"
printf("%*.*d", 6, 3, 12);  // outputs "   012"

Regretfully, there is no equivalent functionality in ostream : the precision is ignored when outputting an integer. (This is probably because there is no type dependent default for the precision. The default is 6, and it applies to all types which respect it.)

使用C ++ setw和setfill中提供的操纵器。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM