2

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;
}
2
  • 1
    Please include the code as text in the question Commented May 14, 2020 at 14:56
  • I just did! Very sorry about that... Commented May 14, 2020 at 15:05

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

It works! Thank you so much for helping me! I really appreciate it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.