1

I want the program to return 4 digits even if the number is less than 4 digits long.
for example:
1 -> 0001 I tried:

printf("%4d",number);

but it only returns three spaces then the number one, it doesn't add the 0s before.

user2864740
  • 60,010
  • 15
  • 145
  • 220
user3924304
  • 33
  • 1
  • 7

2 Answers2

8

By default, white spaces are used for padding, you should add 0 to the format specifier to make the padding character 0s.

printf("%04d",number);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
3

In addition to Yu Hao's answer, you can also specify the digit count dynamically:

printf("%0*d", digit_count, number);
R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187