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?
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.You could use sscanf, and provide '%d' as your format string.
You can do padding on your printf() so if you wanted every output to be 8 characters long you would use
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
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/