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条回答
祖国的老花朵
2楼-- · 2019-09-07 10:03

Don't use atoi. Use strtol with a base of 10.

In general, there's no reason to use atoi in modern code.

查看更多
Viruses.
3楼-- · 2019-09-07 10:03

Most answers assume you want 8 digits while this is not exactly what you requested.

If you want to keep the number of leading zeros, you're probably better keeping it as a string, and convert it with strtol for calculations.

查看更多
Root(大扎)
4楼-- · 2019-09-07 10:05

You could use sscanf, and provide '%d' as your format string.

查看更多
何必那么认真
5楼-- · 2019-09-07 10:06

You can do padding on your printf() so if you wanted every output to be 8 characters long you would use

printf("%08d", number);
查看更多
来,给爷笑一个
6楼-- · 2019-09-07 10:06

Yes, when you want to display ints you have to format them as strings again. An integer is just a number, it doesn't contain any information on how to display it. Luckily, the printf-function already contains this, so that would be something like

printf( "%08d", num);
查看更多
兄弟一词,经得起流年.
7楼-- · 2019-09-07 10:12

You could also count the numbers of numbers in the string and create a new one with leading zeroes.

Or check out all the wonderful format tags for printf and use one to pad with zeroes. Here for example are lot of them: http://www.cplusplus.com/reference/clibrary/cstdio/printf/

查看更多
登录 后发表回答