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
  • 57,407
  • 13
  • 129
  • 202
user3924304
  • 33
  • 1
  • 6

2 Answers2

6

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
  • 115,525
  • 42
  • 225
  • 281
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
  • 72,827
  • 15
  • 131
  • 185