Parameterized Leading Zeros in the C ++ Printf Function

My question is simple. I want to print integers with the specified number of leading zeros using printf. However, the number of leading zeros is determined by the execution time, unknown a priori. How can i do this?

If I knew the number of characters (say 5), that would be

printf("%05d", number); 

But I do not know if it will be 5.

+4
source share
5 answers

You can pass the width using * :

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

You can also use

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

where width_ determined at runtime.

+4
source

I believe that an asterisk can be used to achieve this on most platforms.

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

The standard solution here would be printf("%.*d", precision, number) ; in the printf family in C, the precision formatting field indicates the minimum number of digits to display, the default is 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 width or precision (or both), you can specify '*' , which will cause printf select a value from the argument (pass int ):

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

Unfortunately, there is no equivalent functionality in ostream : accuracy is output when outputting an integer. (This is probably because it is type-independent for accuracy. The default is 6, and applies to all types that respect it.)

+1
source

use the manipulators available in C ++ and install setfill.

-1
source

Source: https://habr.com/ru/post/1411272/


All Articles