Lesson 197 +60 XP

Project 10: Contact Manager with files

Project 10: Contact Manager with files

The final boss: combine classes, vectors, and file I/O. You will build a contact manager that adds contacts in memory, saves them to a file with ofstream, loads them back with ifstream, and reports file errors with try/catch.

The goal

Manage a list of contacts with a menu (do/while), persist them to contacts.txt, and reload them on startup.

What you practice

  • A Contact struct with name and phone
  • A std::vector<Contact> in memory
  • Saving with ofstream and loading with ifstream
  • try/catch for a missing file
  • A do/while menu loop

Starter code

Start from this compile-able core:

#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct Contact {
  string name;
  string phone;
};

void saveContacts(const string& filename, const vector<Contact>& list) {
  ofstream out(filename);
  for (const Contact& c : list) {
    out << c.name << "|" << c.phone << endl;
  }
  out.close();
}

int main() {
  vector<Contact> contacts;
  Contact first{"Ada", "555-0100"};
  contacts.push_back(first);
  saveContacts("contacts.txt", contacts);
  cout << "Saved " << contacts.size() << " contact(s)." << endl;
  return 0;
}

Step-by-step

  1. Run the starter and check that contacts.txt appears with one line.
  2. Write loadContacts(filename, contacts): open with ifstream in(filename); and throw runtime_error if it fails.
  3. Read each line with getline, split on |, and push_back a new Contact.
  4. In main, call loadContacts inside a try and print the message in the catch.
  5. Add a do/while menu: add a contact, list all, save, load, exit.
  6. Close and reopen the program; the saved contacts must come back.

Checklist

  • [ ] ofstream writes each contact to the file
  • [ ] ifstream reads them back on startup
  • [ ] A runtime_error is thrown when the file cannot open
  • [ ] try/catch reports the error instead of crashing
  • [ ] The do/while menu runs at least once
  • [ ] Contacts survive a save and reload round-trip

TL;DR

  • ofstream writes out; ifstream reads in - both need <fstream>.
  • Throw a runtime_error when a file will not open.
  • try/catch turns a crash into a friendly message.
  • A do/while menu always shows once, then loops on choice.