# Getting digits from int.

• 02-21-2003
aker_y3k
Getting digits from int.
Hello, Ive been trying to get the digits that exist in an integer, but I do not really know how to do that. SUppose I have:
PHP Code:

``` int i = 100;  ```
How can I put the different digits into separate variables? For example 1, 0, 0

Thanks.
• 02-21-2003
minesweeper
Use the modulus operator.

eg.

654 % 10 = 4
65 % 10 = 5
6 % 10 = 6

int i = 654 % 10;

i now contains 4
• 02-21-2003
aker_y3k

I will try it. wait.
• 02-21-2003
aker_y3k
Ok, the problem with this, is that I never know the exact number at first. So I cannot really remove the last digit and try again using % 10.

Do you have a work-around for that?
• 02-21-2003
sure. enclose the entire process in a loop looking for a given value. The value is that the number you're working on remains greater than 9. After each modulus, decrease the initial input value by factor of 10. Store each modulus in an array for later use.

Code:

```int input = //whatever int digitArray[12]; int index = -1; while(input > 9) {   digitArray[++index] = input % 10;   input /= 10; }```
• 02-21-2003
Magos
Code:

```#define MaxDigits 8 void SplitDigits(int Number, int* DigitArray) {   for(int i=(MaxDigits-1); i>=0; i++)   {       DigitArray[i] = Number % 10;       Number /= 10;   } } int main() {   int DigitArray[MaxDigits];   int Number = 1538;   SplitDigits(Number, DigitArray);   for(int i=0; i<MaxDigits; i++)   {       cout << DigitArray[i] << endl;   }   return 0; }```
Set a proper value for MaxDigits. In this case, the digits will be 0 0 0 0 1 5 3 8. If you only want the valuable digits (non-preceeding zeros) calculate MaxDigits using 10-logarithm (log10 ? I've never used it) but then you have to modify the arrays to be allocated dynamically.
• 02-21-2003
aker_y3k
Ok, will combine all your posts.

Thank you so much.
• 02-21-2003
aker_y3k
Thanks a lot, it works.!!!!
• 02-21-2003
kiss_psycho
This fragment works for an any digit number (within long limits)

void main()
{
long digit=12345;
while(digit>0)
{
cout<<digit%10<<endl;
digit/=10;
}
}

Happy Hunting...