-
Calling a function
I have a function that gets info for a user.
Code:
istream& operator >> (istream& enter_age, Set& info_set)
{
int x ;
cout << "Enter your age " ;
cin >> x;
age_vector.push_back (x) ;
return enter_age ;
}
I am having trouble calling this function in the main, how should the proper funcyion call look like ?
-
Imagine you are inputting into an int variable from cin, how would you do it? Now do the same, but input into a Set variable.
BTW, you normally don't want to use cout in an operator>> overload. You should also be using the istream parameter, not cin. Finally, if age_vector is a part of the Set class, you probably want to push_back onto the info_set's member.
-
I did try :
Quote:
enter_age >> info_set ;
among other, but I still can't get it to work.
-
You tried that as the code to call the function in main, or you tried it inside the function? Inside the function it is wrong because that will just call the function again over and over. You are supposed to be implementing how that works. If that's what you used in main, it might work but it depends on how you declare enter_age and info_set in main.
-
I am trying to call it in the main, which is only:
Code:
int main()
{
Set enter_age ;
Set info_set ;
enter_age >> info_set ;
system("PAUSE");
return 0;
}
I am geting 2 compile-time errors:
1) 42 d:\docume~1\suchy\desktop\operat~1.cpp
no match for `Set & >> Set &'
2) 25 d:\docume~1\suchy\desktop\operat~1.cpp
candidates are: class istream & operator >>(istream &, Set &)
I spent couple of hours playing around with this and I still cant get it right.
-
Is this what you are trying to do ?
Code:
#include <iostream>
#include <vector>
using std::cout;
using std::cin;
using std::endl;
using std::vector;
class inputter { // just a dummy to satisfy operator >>
};
class Set {
public:
void push_back (int x) { cout << "entered " << x << " into Set." << endl; v.push_back(x); }
void print() { for ( vector<int>::iterator i = v.begin(); i != v.end(); ++i ) cout << "age=" << *i << endl; }
vector<int> v;
};
inputter & operator >> (inputter & enter_age, Set& info_set) {
int x ;
cout << "Enter your age " ;
cin >> x;
info_set.push_back (x) ;
return enter_age;
}
int main() {
inputter enter_age;
Set info_set ;
// enter 3 values into info_set
enter_age >> info_set >> info_set >> info_set;
info_set.print();
return 0;
}
It shure looks strange to use operator >> this way.
Kurt
-
I don't think that's what Suchy is trying to do. I think the goal is just to read from cin.
Suchy, how would you read in an int from cin? If I was to translate your code above to read in an int it would look like this:
Code:
int main()
{
int enter_age;
int info_int;
enter_age >> info_set ;
system("PAUSE");
return 0;
}
But that's not how you would read in an int with cin. So try to find the code that would read in an integer, and then do exactly the same, but use a Set instead of an int.