c++ - 将向量写入文件c ++
问题描述
在这里,我有一个称为联系人的结构
typedef struct contacts
{
string name; //{jhonathan , anderson , felicia}
string nickName; //{jhonny , andy , felic}
string phoneNumber; // {13453514 ,148039 , 328490}
string carrier; // {atandt , coolmobiles , atandt }
string address; // {1bcd , gfhs ,jhtd }
} contactDetails;
vector <contactDetails> proContactFile;
我正在尝试将向量中的数据写入输出文件。为此,我编写了以下代码
ofstream output_file("temp.csv");
ostream_iterator<contactDetails> output_iterator(output_file, "\n");
copy(begin(proContactFile),end(proContactFile), output_iterator);
但是这段代码总是给我一个错误。另外我想用以下方式将数据写入文件。
Name,Nick name,Phone number,Carrier,Address
我的代码有什么问题?
解决方案
std::ostream_iterator<T>
调用operator<<
类型T
。您需要编写代码std::ostream& operator<<(std::ostream& os, const contactDetails& cont)
以便ostream_iterator
迭代并写入其输出流。
typedef struct contacts
{
string name; //{jhonathan , anderson , felicia}
string nickName; //{jhonny , andy , felic}
string phoneNumber; // {13453514 ,148039 , 328490}
string carrier; // {atandt , coolmobiles , atandt }
string address; // {1bcd , gfhs ,jhtd }
} contactDetails;
vector <contactDetails> proContactFile;
std::ostream& operator<<(std::ostream& os, const contactDetails& cont)
{
os << cont.name << "," << cont.nickName << ",";
os << cont.phoneNumber << "," << cont.carrier << ",";
os << cont.address << endl;
return os;
}
推荐阅读
- java - 如何使用 Mockito 或 PowerMock 在类中设置私有字段
- apache-kafka - Kafka消费者消息提交问题
- css - Angular Material & Flex:如何为整个应用设置最大宽度?
- reactjs - Redux 选择器或效果器
- java - CompoundIndexes 注释在 MongoDB 和 Spring 中不起作用
- azure - 将事件从 Azure 事件中心传送到 Azure 服务总线
- javascript - 如何通过单击表格行来检查单选按钮?
- python - 如何制作分类列计数子集的条形图?
- mongodb - 当其中一个字段位于子文档数组中时,如何从集合中获取两个字段的不同组合
- javascript - 有没有办法使用javascript在cookie中存储hrefs