Casa_De_Agua
Casa_De_Agua

Reputation: 181

How do I assign the digits of int to array c++

Bear with me, I'm fairly new.

What I am trying to do is get what the user inputs to be separated into digits into an array so for example:

    int digits[10] = {0}   //initialize
    int input = 12345;     // length was defined earlier, and in this case is "5"

    for (unsigned int i = 1; i <= length; i++) {

        digits[i - 1] = (input / (10 ^ (i - 1))) % 10;      // supposed to seperate digits in reverse order
                                                            // 12345 --> digits[] --> { 5, 4, 3, 2, 1 }
                                                            // currently not working
    }

I was testing it to makes sure that i was doing this right and have the array printed to the screen but I got back: 11234

I tried different numbers and for example, 22222 prints out : 79702

code for printing the array:

        for (int k = length - 1; k >= 0; k--) {
            cout << digits[k] << endl;
    }

I know I'm missing something, but thanks in advance

Upvotes: 2

Views: 59

Answers (1)

Jacob Panikulam
Jacob Panikulam

Reputation: 1218

Your math is exactly correct, but you have made a very reasonably syntax mistake.

The ^ operator in C++ is bitwise xor, not exponentiation. You will want to use std::pow(base, exponent).

Upvotes: 4

Related Questions