This project is a stripped-down version of a contact book, great for beginners. We’ll use a map to store contacts (name → number) and simple file I/O to save and load data.
Simple Contact Book in C++ Using map and File I/O
What This Program Does
-
Adds new contacts
-
Displays all contacts
-
Saves contacts to a text file
-
Loads contacts at startup
#include <iostream>
#include <map>
#include <fstream>
using namespace std;
map<string, string> contacts;
void saveToFile() {
ofstream outFile("contacts.txt");
map<string, string>::iterator it;
for (it = contacts.begin(); it != contacts.end(); it++) {
outFile << it->first << "," << it->second << endl;
}
outFile.close();
}
void loadFromFile() {
ifstream inFile("contacts.txt");
string line,name,number;
while (getline(inFile,line)){
int pos = line.find(',');
if (pos != string::npos) {
name = line.substr(0, pos);
number = line.substr(pos + 1);
contacts[name] = number;
}
}
inFile.close();
}
void showContacts() {
cout << "---- Contact List ----" << endl;
map<string, string>::iterator it;
for (it = contacts.begin(); it != contacts.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
}
int main() {
loadFromFile();
contacts["Alice"] = "9876543210";
contacts["Bob"] = "9123456780";
saveToFile();
showContacts();
return 0;
}
Output: ---- Contact List ---- Alice: 9876543210 Bob: 9123456780