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?
Use strtol instead. It allows you to specify the base.
If you don't want that behavior; don't use atoi.
Perhaps sscanf with a %d format?
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.