I'm have trouble printing out a vector of my own class, vector<Data> data;
.
Briefly, I'm working on a class class Data_proc
, it has a constructor under public:
explicit Data_proc(const string& n, istream& is)
{
Data temp;
while(is >> temp)
this->data.push_back(temp);
}
I have also overloaded operator<<
for printing:
friend ostream& operator<<(ostream& os, const Data_proc& dp)
{
os << "Person: " << dp.name
<< "\nnumber: " << dp.number;
copy(dp.data.begin(), dp.data.end(), ostream_iterator<Data>(cout));
return os;
}
The problem here is that code compiles with no problems, but nothing from the data vector is being printed out to the console. However, when I altered my constructor as following, it works, partially:
Data temp;
is >> temp;
data.push_back(temp);
But as you might have suspected, this only prints out the first "pair", and the rest of data that were read from file are discard. What did I do wrong? Why didn't the while
-loop keep reading from the file? Any help are appreciated! If you need details about the class Data
, let me know!
Edit: operator>>
for data, where I have string staffName
and vector<int> passCode
:
friend istream& operator>>(istream& is, Data& d)
{
getline(is, d.staffName, '\n');
int temp;
while(is >> temp)
d.passCode.push_back(temp);
return is;
}
I can paste a snippet of how a input file's content looks like if it's also needed!
Edit 2: Added operator<<
for class Data
:
friend ostream& operator<<(ostream& os, const Data& d)
{
os << d.staffName<< "\n";
copy(d.passCode.begin(), d.passCode.end(), ostream_iterator<int>(cout, " "));
return os;
}
Edit 3: Made a new operator>>
:
getline(is, d.staffName, '\n');
string results;
getline(is, results, '\n');
istringstream iss(results);
int val;
while(iss >> val)
d.passCode.push_back(val);
return is;
In your
operator>>
This reads ints from the stream until failure. So whether it runs to the end of the stream, or until it tries to read something that cannot be interpreted as an int, the stream is guaranteed to be in a failure state when time the function ends. This means that in your constructor, the expression
is >> temp
will report as failed no matter the contents of the file, and no items will be put in the vector.