3

在对向量进行必要的更改后,我目前正在尝试将向量复制到新的文本文件中。我可以很好地构建项目,但它给了我不明白的奇怪错误。谁能帮我解决这个问题?

我的结构

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

给我错误的代码

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

有一大堆错误行,但我认为这应该是重要的两行: 在此处输入图像描述

4

2 回答 2

3

您需要operator<<AccDetails. 这就是ostream_iterator所谓的内在。

像这样的东西:

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;
}

运算符将其插入的流作为第一个参数,并将对它正在流式传输的对象的常量引用作为第二个参数(这AccDetails也允许传递临时 )。现在你也可以说:

AccDetails acc;
std::cout << acc;

如果操作员需要访问AccDetail的私有字段,则需要声明为friend.

如果您不熟悉运算符重载,我建议您阅读此 SO 线程

希望有帮助。

于 2013-07-31T11:03:38.270 回答
2

正如 jrok 所说,重载后可以有这个:

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); 

}
于 2013-07-31T12:04:39.737 回答