首页 > 解决方案 > 将向量写入文件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

我的代码有什么问题?

标签: c++vectorstructfile-io

解决方案


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

推荐阅读