Loading lessons...
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
Contactstruct withnameandphone - A
std::vector<Contact>in memory - Saving with
ofstreamand loading withifstream try/catchfor a missing file- A
do/whilemenu 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
- Run the starter and check that
contacts.txtappears with one line. - Write
loadContacts(filename, contacts): open withifstream in(filename);and throwruntime_errorif it fails. - Read each line with
getline, split on|, andpush_backa newContact. - In
main, callloadContactsinside atryand print the message in thecatch. - Add a
do/whilemenu: add a contact, list all, save, load, exit. - Close and reopen the program; the saved contacts must come back.
Checklist
- [ ]
ofstreamwrites each contact to the file - [ ]
ifstreamreads them back on startup - [ ] A
runtime_erroris thrown when the file cannot open - [ ]
try/catchreports the error instead of crashing - [ ] The
do/whilemenu runs at least once - [ ] Contacts survive a save and reload round-trip
TL;DR
ofstreamwrites out;ifstreamreads in - both need<fstream>.- Throw a
runtime_errorwhen a file will not open. try/catchturns a crash into a friendly message.- A
do/whilemenu always shows once, then loops on choice.