Search code examples
c++arraysostream

Print array into textfile


i'm currently trying to print a file's contents into a text file, but the data that comes out is simply an address. If anyone could give me advice it'd be much appreciated.

ostream& operator<<(ostream& out, const BusinessContact& Con)
{
  out << Con.firstName << " "
  << Con.lastName << " "
  << Con.phoneNumber<< " "
  << Con.emailAddress<< " "
  << Con.company << " "<<endl;
  return out;
}

BusinessContact* Alfred = new BusinessContact("Alfred", "Butler", "999-999-9999", "[email protected]", "Gotham");
BusinessContact* Bruce  = new BusinessContact("Bruce", "Wayne", "999-999-0000", "[email protected]", "Gotham");
BusinessContact* Clark  = new BusinessContact("Clark", "Kent", "888-888-8888", "[email protected]", "Metropolis");
BusinessContact* Luther = new BusinessContact ("Lex", "Luther", "888-888-1313", "[email protected]", "Metropolis");

array<BusinessContact*, 10> listBContacts{Alfred, Bruce, Clark, Luther};

void arrayTransform()
{
try
{
    cout << "Write Contacts to file..." << endl;
    ofstream OUT("Contacts.txt", ios::out);
    if (!OUT)
        throw new string("Contacts.txt not opened... ");
        for (int i = 0; i < listBContacts.size(); ++i)
        {
            OUT << listBContacts[i];
        }   OUT.close();
            system("pause");
} catch(string*msg)
    {
        cerr<< "Exception: " << *msg << endl;
    }
}

Solution

  • Array listBContacts contains pointers, not values. You need to dereference pointers first to be able to print them: OUT << *(listBContacts[i]);