Overloading Output for a pointer to an array in a class

Hey yall, so I have once again stumbled upon an overloading problem. For this class project, we pretty much have to make a class for a type that handles extra large integers (up to 40 digits). Part of the assignment is overloading the output operator so we could just do "cout<<obj" and that's where I'm having trouble. The array is stored in private as just a pointer to the beginning of the array. The array is size 40 and stores the number itself at the end of the array i.e. {0,0,0,0,0,0......,9,9,9,9} = 9999 etc. I have attached what I have so far, but it just prints out nothing. arrSize is the size of the array, numSize is the size of the number in the array, and ptr is the array itself, also I only want the number itself, not the leading zeros. If anyone has any ideas or tips I would greatly appreciate them.

1
2
3
4
5
6
7
8
friend std::ostream &operator<<(std::ostream &output, const myInteger &obj)
    {
        for(auto i = arrSize-numSize; i < numSize; ++i)
        {
        output << obj.ptr[i];
        }
    return output;
    }
 
i < arrSize     (or presumably obj.arrSize)

Last edited on
Your have a few problems, all related to line 3.

1) Lets assume numSize is 10. i will start at 30. Your termination condition is i < 10. Because I starts at 30, line 5 will never execute. Try this:
 
    for(auto i = arrSize-numSize; i < arrSize; ++i)


2) numSize should should be a member of myInteger. That way your operator will work correctly with any myInteger that is passed.

I tried that condition and it worked better, but now it is only outputting the final digit of the object (if the object is {1234} it prints n1 is 4). numSize is a member of my class but it had to be static and initialized outside of the class itself to be used there. IDK if that caused any problems but I know it may have. I think my a big issue is the arrSize-numSize, but that's the only way i could think of passing over the leading zero's. I know there's probably some fancy function or secret c++ command I don't know about, but that's what i got for now.
numSize is a member of my class but it had to be static and initialized outside of the class itself to be used there.

You're missing the point of my #2. numSize should not be static. Consider that you may have two myIntegers in your program with different number of digits. How are you going to print those? You certainly don't want to modify numSize before printing each one. For example, the following:
1
2
3
4
 
    myInteger obj1 ("123456789");  //  Each ctor sets numSize appropriately
    myInteger obj2 ("123");
    cout << obj1 << "+" << obj2 << endl;


I tried that condition and it worked better, but now it is only outputting the final digit of the object (if the object is {1234} it prints n1 is 4).

If the code I posted previously is not working, numSize or arrSize are not correct.
Topic archived. No new replies allowed.