I have a class with a constructor that takes a vector as an argument and some member functions that operate on the vector:
class myclass{
vector<double> myvec;
public:
myclass(){ cout << "Constructor 1 " << endl; }
myclass(const vector <double> &v){ "Constructor 2 " << endl; }
ostream& print(ostream &s) const { //print function used in overloading output operator }
double minimum(){ //return min value of vector }
double maximum(){ //return max value of vector }
};
I have overloaded the input operator to take the values of a vector in a specific format: "<5: 1 2 3 4 5>" :
istream& operator>>(istream &s, myclass &mc) {
int size;
double item;
vector<double> tempvec;
char lpar, colon, rpar;
if (s >> lpar) {
if ((s >> size >> colon) && (lpar == '<' && colon == ':')){
tempvec[size];
while(s >> item && rpar != '>'){
tempvec.push_back(item);
}
mc = myclass(tempvec);
s >> rpar;
}else{
s.setstate(ios::badbit);
}
}
return s;
}
I go to test my code:
int main(){
myclass mc;
cout << "Main Start" << endl;
while (cin >> mc)
cout << mc << endl << mc.minimum() << endl << mc.maximum() << endl;
if (cin.bad()) cerr << "\nBad input\n\n";
cout << "Main Start" << endl;
return (0);
}
I run the code input the values in the format "<5: 1 2 3 4 5>", but instead of getting the min and max value printed out all I get is:
Constructor 1
Main Start
<5: 1 2 3 4 5>
Constructor 2
Main End
If I change the while loop in the operator overloading to:
while(s >> item >> rpar && rpar != '>'){
tempvec.push_back(item);
}
mc = myclass(myvec);
I get the min and max when I test the code in main but only get half the inputs:
Constructor 1
Main Start
<5: 1 2 3 4 5>
Constructor 2
<2: 1 3>
1
3
I understand why this is: item = 1, rpar = 2, rpar is not equal to '>', myvec.pushback(1) and so on...
So I think the error might to do with the while loop, but I'm not sure where I'm going wrong.
Edit:
So I included a count to compare the number of inputs to the size:
while(s >> item && count < size && rpar != '>'){
tempvec.push_back(item);
++count; // count++ doesnt change anything
}
mc = myclass(tempvec);
s >> rpar;
I now get:
Constructor 1
Main Start
<5: 1 2 3 4 5>
Constructor 2
<4: 1 2 3 4>
1
4
Main End
The last value is not being included.