I'm having trouble with getting the digits out of an integer.
Here is my assignment instructions.
Define a class named MyInteger that stores an integer. It has default and argument constructor(s), and has functions to get and set the integer value. Overload the [] operator so that the index returns the digit in position i, where i=0 is the least significant digit. If no such digit exists,then -1 should be returned. This [] operator should not change the integer value of the object. For example, if x is of type MyInteger and is set to 418, then x[0] should return 8, x[1] should return 1, x[2] should return 4, and x[3] should return -1
This is the class I have made:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
class MyInteger
{
private:
int x;
public:
MyInteger() {
x = 0;
};
MyInteger(int a) {
x = a;
};
int get;
void set(int a) { x = a; };
//Overloaded subscript operator
int& operator[] (const int index);
};
|
But how can I define the operator[] to get the digit of an integer? Isn't this only to be used for an array? ints dont work like strings, do they?
So far, I have
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
int MyInteger::operator[] (const int index)
{
string strx = to_string(x);
if (index == 0)
{
return (x % 10);
}
else if (index <= strx.length())
{
return (x / (index * 10) % 10);
}
else
return -1;
}
|
But when it comes to the last(first) integer, it returns 0