atoi and leading 0's for decimal numbers

2019-09-07 09:22发布

When using atoi in C I am trying to convert a char array of numbers to an int. I have leading 0's on my number though and they are not preserved when I print the number out later.

char num[] = "00905607";
int number;

number = atoi(num);

printf("%d", number);

The output from this will be 905607 and I would like it to be 00905607.

Any ideas?

标签: c decimal atoi
9条回答
Emotional °昔
2楼-- · 2019-09-07 10:17

Use strtol instead. It allows you to specify the base.

查看更多
一纸荒年 Trace。
3楼-- · 2019-09-07 10:17

If you don't want that behavior; don't use atoi.

Perhaps sscanf with a %d format?

查看更多
Rolldiameter
4楼-- · 2019-09-07 10:23

That code is working properly, if it works at all. The integer is 905607... leading zeros don't exist in a mathematical sense.

You have a lot of issues with that code. You're declaring your string improperly, and you're not printing the converted number. Also, if you were doing printf(number); you'd need to use a format string. If you'd like to have leading spaces in that, you can use a width specifier.

查看更多
登录 后发表回答