mercredi 15 avril 2015

How can I std::copy a string to a struct with the std::string fields

I read from a file lots of records into a std::vector like this:



std::fstream in("storage.txt", std::ios::in);
stxxl::vector<Citizen> v;
std::copy(std::istream_iterator<Citizen>(in), std::istream_iterator<Citizen>(), std::back_inserter(v));


The struct Citizen is defined as:



struct Citizen
{
std::string firstname, lastname;
int year;
};


That function is created for the isteam_iterator:



std::istream& operator >>(std::istream& i, Citizen& c)
{
i >> c.firstname >> c.lastname >> c.year;
return i;
}


During creation of the first struct I get a segmentation fault. Why? I know, the struct's string fields have not enough space. Changing the type to char fieldname[some size] solves the problem, but it is a C style and I don't want to use it.


How can I allocate space for that example?


Aucun commentaire:

Enregistrer un commentaire