atoi and leading 0's for decimal numbers
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?
You can do padding on your printf() so if you wanted every output to be 8 characters long you would use
printf("%08d", number);
Use strtol instead. It allows you to specify the base.
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.
Don't use atoi. Use strtol with a base of 10.
In general, there's no reason to use atoi in modern code.
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.
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);
You could use sscanf, and provide '%d' as your format string.
If you don't want that behavior; don't use atoi.
Perhaps sscanf with a %d format?
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/
char num[] = "00905607";
int number;
number = atoi(num);
printf("%0*d", (int)strlen(num), number);
精彩评论