[Solved] % operator not working with integer variables


I’m only writing this because the other answers are dangerously wrong.

Here is a simple, slow and fool-proof solution:

#include <iostream>
#include<cmath>
int getDigit(int num, int index)
{
    // first shift index -1 digits to the right to position the indexth digit
    while(--index)
    {
        num /= 10;
    }
    // now strip off everything after the indexth digit
    num %= 10;
    // could be negative, but we only want digit. Lose the sign
    return std::abs(num);
}

int main()
{
    std::cout <<getDigit(6947, 3) << std::endl;
}

Output

9

Here is a faster, less safe non-portable solution that only works with a 32 bit integer.

int divisors[] =
{
    1,
    10,
    100,
    1000,
    10000,
    100000,
    10000000,
    100000000,
    1000000000,
};
int getDigit32(int num, int index)
{
    if (index <=10)
    {
        return std::abs((num/divisors[index -1])%10);
    }
    return -1;
}

I think it can be generalized by generating the array with template meta programming, but I’ll be honest and admit I’m not good at that stuff. I’m struggling to find a good terminating condition.

solved % operator not working with integer variables