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;
}