You are here:

C++/Integer class

Advertisement


Question
I am trying to write an integer class that allows the user to enter a number 10 digits long. I am trying to overload the [] operator so that the index returns the digit in position i, where i=0 is the least significant digit. I am having problems with this part of the code.

I have written the rest of the code. So far it will accept a number, then it prints the number entered instead of each digit separately.

Answer
Hello Jacob.

I assume that you are storing the number in your class as an integer, and that you want to return the digit as an integer.

Lets say that mValue is the integer stored in you class.

The operator[] is like this:

int operator[](int index)
{
   int x = mValue / (int)pow(10.0, index);
   return x % 10;
}

The first line divides the integer mValue by a power of 10 so that the desired digit is at the end.
The second line picks off the last digit and returns it.
You can combine the two lines into one.

You will need to include math.h to get the pow function.

Does that make sense? Feel free to follow up if you don't understand something.

Some things to investigate:
What happens if mValue is negative ?
What happens if your index value is greater than the number of digits in mValue ?

Best regards
Zlatko

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.