问题
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?
回答1:
Use
char s[] = "0929784";
size_t len = strlen(s);
long temp = strtol(s, NULL, 10);
printf("%0*li", (int) len, temp);
Details are here.
A more subtle and even safer approach would be:
char s[] = "0929784FooBarBlaBla";
char * endptr;
long temp = strtol(s, &endptr, 10);
printf("%0*li", (int) (endptr - s), temp);
More details are here.
回答2:
printf
will print the long
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 were 28
would you? Even more sinister in C, a leading 0 denotes an octal constant, so actually 028
makes no sense as a number in C. Formally 0
is an octal constant although that, of course, doesn't matter.
回答3:
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:
0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;
So use:
printf("%0*li", (int) strlen(s), temp);
回答4:
Yes. Try
printf("%07li", temp);
来源:https://stackoverflow.com/questions/49851981/why-does-string-to-int-conversion-not-print-the-number-0-if-its-at-first-index