Quantcast
Viewing latest article 12
Browse Latest Browse All 12

Answer by chqrlie for Printing leading 0's in C

There are 2 ways to output your number with leading zeroes:

Using the 0 flag and the width specifier:

int zipcode = 123;printf("%05d\n", zipcode);  // outputs 00123

Using the precision specifier:

int zipcode = 123;printf("%.5d\n", zipcode);  // outputs 00123

The difference between these is the handling of negative numbers:

printf("%05d\n", -123);  // outputs -0123 (pad to 5 characters)printf("%.5d\n", -123);  // outputs -00123 (pad to 5 digits)

Zip codes are unlikely to be negative, so it should not matter.

Note however that zip codes may actually contain letters and dashes, so they should be stored as strings. Including the leading zeroes in the string is straightforward so it solves your problem in a much simpler way.

Note that in both examples above, the 5 width or precision values can be specified as an int argument:

int width = 5;printf("%0*d\n", width, 123);  // outputs 00123printf("%.*d\n", width, 123);  // outputs 00123

There is one more trick to know: a precision of 0 causes no output for the value 0:

printf("|%0d|%0d|\n", 0, 1);  // outputs |0|1|printf("|%.0d|%.0d|\n", 0, 1);  // outputs ||1|

Viewing latest article 12
Browse Latest Browse All 12

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>