Why does string to int conversion not print the number 0 if its at first index [duplicate]

让人想犯罪 __ 提交于 2019-12-11 15:43:50

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!