Why does string to int conversion not print the nu

2019-08-30 06:14发布

This question already has an answer here:

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?

标签: c atoi strtol
4条回答
来,给爷笑一个
2楼-- · 2019-08-30 06:45

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楼-- · 2019-08-30 06:47

Yes. Try

printf("%07li", temp);
查看更多
We Are One
4楼-- · 2019-08-30 06:52

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);
查看更多
叛逆
5楼-- · 2019-08-30 07:00

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.

查看更多
登录 后发表回答