Input operator overloading with a function

Viewed 149

I am a bit new at C++ and I have to solve the following exercise:

I have to create an object of class Sum(limit) where the user can input numbers until the sum of all the inputs reaches the limit.

The main function has to look like this and cannot be changed:

int main (){
    Sum sum(100);
    std::cout << "Enter numbers\n";
    do{
        std::cin >> sum;
    } while (!sum.exceededlimit());
    std::cout << "The sum of all the components is : " << sum() << "\n";
    return 0;
}

So I created the class in which I put an empty vector. For now, the problem that I have is how to overload the input operator so that the input can go directly in the vector of the object.

This is what I have tried until now (I didn't try the limit part, I am just trying to add input to a vector for now) but it seems to have a problem with input>>c.newnumber(input);

Thanks a lot if you take the time to help me.

Code:

#include <iostream>
#include <vector>

class Sum {
    private:
        int limit;
    public:
        std::vector<int> vect;
        int newnumber(int x){
        vect.push_back(x);}
        Sum(int x);
};

std::istream & operator>>(std::istream &input, Sum & c){
    input>>c.newnumber(input);
    return input;
}


Sum::Sum(int x) {
    limit=x;
}

int main () {
    Sum sum(100);
    std::cin >> sum;
    std::cin >> sum;
    std::cin >> sum;
    std::cin >> sum;
    std::cin >> sum;
    return 0;
}
1 Answers

Let's look at what we have to work with here...

You have a newnumber() function that'll take an int and add it to your Sum object.

In your insertion operator overload, you're given a Sum object and an istream object. We know we have newnumber() on the Sum object, but we can only use it if we have an int! So how can we get an int from the istream to then pass to your Sum?

I'd do it like:

std::istream & operator>>(std::istream &input, Sum & c){
    int val;
    input >> val;
    // Maybe do some validation checking here?
    c.newnumber(val);
    return input;
}
Related