Writing a vector to a file c++

83 views Asked by At

Here I have a structure called contacts

 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;

I'm trying to write the data inside my vector to a output file.For this i've written the following code

    ofstream output_file("temp.csv");
    ostream_iterator<contactDetails> output_iterator(output_file, "\n");
    copy(begin(proContactFile),end(proContactFile), output_iterator);

But this code always gives me an error.Also I want to write the data to the file with the following way.

Name,Nick name,Phone number,Carrier,Address

Whats wrong with my code?

2

There are 2 answers

7
John Park On

std::ostream_iterator<T> invokes operator<< for the type T. You need to write code for std::ostream& operator<<(std::ostream& os, const contactDetails& cont) so that ostream_iterator iterates and write to its output stream.

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;
}
1
SeektheFreak On
void deleteContact() //Delete Feature
{
    ofstream output_file("temp.csv");
    int selectContact;
    cout << "Which Contact you want to delete ? Enter the relevent index " << endl;
    cin >> selectContact;
    
    if (selectContact > proContactFile.size()) {
        cout << "Invalid entry";
    }
    else {
        proContactFile.erase(proContactFile.begin() + (selectContact - 1));
        cout << "Delete successfully";
    }
   
    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;
    }
    output_file.close();
}

Hey Now the previous error is gone.Now it just says expected a ';'.But nothings missing here.