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:
How can I put the different digits into separate variables? For example 1, 0, 0PHP Code:
int i = 100;
Thanks.
Printable View
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:
How can I put the different digits into separate variables? For example 1, 0, 0PHP Code:
int i = 100;
Thanks.
Use the modulus operator.
eg.
654 % 10 = 4
65 % 10 = 5
6 % 10 = 6
int i = 654 % 10;
i now contains 4
Oh I see, helpful!
I will try it. wait.
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?
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;
}
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.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;
}
Ok, will combine all your posts.
Thank you so much.
Thanks a lot, it works.!!!!
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...