c++ - Copy vector struct to file using ostream_iterator and copy -
i'm trying copy vector new text file after making necessary changes vector. can build project fine, giving me weird errors don't understand. possibly me this?
my struct
class accdetails { public: string username; string name; string topicid; string testid; };
the code giving me errors
vector<accdetails>accinfo; ofstream temp ("temp.txt"); ostream_iterator<accdetails>temp_itr(temp,"\n"); copy(accinfo.begin(),accinfo.end(),temp_itr);
there's whole chunk of error lines, think should important 2 lines:
you'll need overload operator<<
accdetails
. ostream_iterator
calls internaly.
something this:
std::ostream& operator<<(std::ostream& stream, const accdetails& obj) { // insert objects fields in stream 1 one along // description , formatting: stream << "user name: " << obj.username << '\n' << "real name: " << obj.name << '\n' << obj.topicid << ' ' << obj.testid << '\n'; return stream; }
the operator takes stream inserts first parameter , constant reference object streaming second 1 (this allows passing temporary accdetails
, too). can say:
accdetails acc; std::cout << acc;
if operator need access accdetail
's private fields, need declare friend
.
if you're new operator overloading, suggest read this thread.
hope helps.
Comments
Post a Comment