the following code is not behaving like I would expect. Please help me understand how it works.
#include <algorithm>
#include <iterator>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
struct user
{
string name;
string age;
string id;
};
istream& operator>>(istream& is, user& s)
{
getline(is, s.name, ':');
getline(is, s.age, ':');
getline(is, s.id);
return is;
}
int main(int argc, char* argv[])
{
ifstream file("file.txt");
vector<user> vec;
copy(istream_iterator<user>(file), istream_iterator<user>(), back_inserter(vec));
return 0;
}
My custom operator>> is called twice but I would expect it to be called only once because the contents are:
John:forty:21-5821-0
copy
code was causing the read, rather than the dereferencing, so it performs one read too many. That said, youroperator >>
needs to check the status after the first twogetline
operations! – Flopeared&&
will turn them into abool
, no? – Homoeroticism