This question already has an answer here:
- Keep Leading zeros C 2 answers
- keeping leading zeros in C [duplicate] 3 answers
I am wondering as to why when converting strings to int with either atoi or strtol it does not print the number 0 if its the first index, take this code for example
char s[] = "0929784";
long temp = strtol(s, NULL, 10);
printf("%li", temp);
OUTPUT: 929784
is there a way to have the 0 print?
printf
will print thelong
in the best way possible, and that includes dropping any leading zeros.For example, if someone asks you to write your age, you wouldn't write
028
if you were28
would you? Even more sinister in C, a leading 0 denotes an octal constant, so actually028
makes no sense as a number in C. Formally0
is an octal constant although that, of course, doesn't matter.Yes. Try
An int basically stores leading zeros. The problem that you are running into is that you are not printing the leading zeros that are there. (source)
printf
manual:So use:
Use
Details are here.
A more subtle and even safer approach would be:
More details are here.