Ilyssis Ilyssis - 2 months ago 14
C++ Question

C++ get each digit in int

I have an integer:

int iNums = 12476;


And now I want to get each digit from iNums as integer. Something like:

foreach(iNum in iNums){
printf("%i-", iNum);
}


So the output would be: "1-2-4-7-6-".
But i actually need each digit as int not as char.

Thanks for help.

Answer
int iNums = 12345;
int iNumsSize = 5;
for (int i=iNumsSize-1; i>=0; i--) {
    int y = pow(10, i);
    int z = iNums/y;
    int x2 = iNums / (y * 10);
    printf("%d-",z - x2*10 );
}
Comments