atoi and leading 0's for decimal numbers

2019-09-07 09:57发布

问题:

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?

回答1:

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



回答2:

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

printf("%08d", number);


回答3:

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.



回答4:

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

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



回答5:

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);


回答6:

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.



回答7:

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



回答8:

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

Perhaps sscanf with a %d format?



回答9:

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/



标签: c decimal atoi