A.A
A.A

Reputation: 39

How to get the digits from an int value and append it into an array

I want to append the number(value) digit by digit into the destination array but how would I iterate "i" backwards? I am saying this because I want to use v / 10^i % 10 which would get me the digit of any place I want using i where i = 0 is the low order digit and v is the value. Here is what I did so far:

value = va_arg( ap, int); 
       //value is the int value
       while(value > 0) {
          unsigned int digit1 = value / pow(10,i) % 10

          append( &dest, &len, &cap, digit1 + 048);

       }

The append part can be ignored since it doesn't relate to the problem except the last parameter. The last parameter is expecting a character. I have not set "i" since I am not sure how to iterate i. Any help would be appreciated.

Upvotes: 0

Views: 59

Answers (2)

ssd
ssd

Reputation: 2422

Some code like below would work w/o using library functions.

int value = 234873485;
int digit;
int tmpValue = value;
int i = 0;
int arr[10] = {0};

while (tmpValue > 1) {
    tmpValue /= 10;
    i++;
}

tmpValue = value;

while (tmpValue > 1) {
    digit = tmpValue % 10;
    printf("%d\n", digit); // may be replaced to append array
    arr[i--] = digit;      // something like this one
    tmpValue /= 10;
}

Upvotes: 0

davidlowryduda
davidlowryduda

Reputation: 2549

The number of digits will be the smallest integer greater than log10(value). So you know exactly what elements of your array will be filled.

Alternately, you could form your array incrementally and then reverse it if you want it in the opposite order.

Upvotes: 1

Related Questions