Question

I'm currently trying to copy a vector to a new text file after making the necessary changes to the vector. I can build the project fine, but its giving me weird errors that I don't understand. Could anyone possibly help me with this?

My struct

class AccDetails {
public:
    string username;
    string name;
    string topicid;
    string testid;
};

The code that is giving me the errors

vector<AccDetails>accInfo;
ofstream temp ("temp.txt");
ostream_iterator<AccDetails>temp_itr(temp,"\n");
copy(accInfo.begin(),accInfo.end(),temp_itr); 

There's a whole chunk of error lines, but i think this should be the important 2 lines: enter image description here

Was it helpful?

Solution

You'll need to overload operator<< for AccDetails. It is what ostream_iterator calls internaly.

Something like this:

std::ostream& operator<<(std::ostream& stream, const AccDetails& obj)
{   
    // insert objects fields in the stream one by one along with some
    // description and formatting:

    stream << "User Name: " << obj.username << '\n'
           << "Real Name: " << obj.name << '\n'
           << obj.topicid << ' ' << obj.testid << '\n';

    return stream;
}

The operator takes the stream it inserts to as first parameter and a constant reference to the object it is streaming as the second one (this allows passing temporary AccDetails, too). Now you can also say:

AccDetails acc;
std::cout << acc;

If the operator would need access to AccDetail's private fields, you would need to declare as a friend.

If you're new to operator overloading, I suggest you read this SO thread.

Hope that helps.

OTHER TIPS

Can have this after overloading as jrok said:

class AccDetails 
{

    std::string username;
    std::string name;
    std::string topicid;
    std::string testid;

    friend std::ostream& operator<<(std::ostream&, const AccDetails&);
    friend std::istream& operator>>(std::istream& is,  AccDetails& );
};

std::ostream& operator<<(std::ostream& os, const AccDetails& acc)
{
    os  << "User Name: " << acc.username << std::endl
           << "Name: " << acc.name << std::endl
           << acc.topicid << ' ' << acc.testid << std::endl;
    return os;
}

std::istream& operator>>(std::istream& is,  AccDetails& acc)
{   
    is >> acc.username >>acc.name >> acc.topicid >> acc.testid ;
    return is;
}


int main()
{

std::vector<AccDetails>accInfo;

std::copy(std::istream_iterator<AccDetails>(std::cin),
    std::istream_iterator<AccDetails>(),std::back_inserter(accInfo) ); 

std::ofstream temp("temp.txt",std::ios::out);
std::ostream_iterator<AccDetails>temp_itr(temp,"\n");
std::copy(accInfo.begin(),accInfo.end(),temp_itr); 

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top