BCA
Object Oriented Programming using C++ Practical
Madras University
Program 12
Implement a telephone directory using files
SOURCE CODE:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
struct Contact {
string name;
string phoneNumber;
};
void addContact(const Contact& contact) {
ofstream outFile("directory.txt", ios::app); // Open file in append mode
if (outFile.is_open()) {
outFile << contact.name << "," << contact.phoneNumber << endl;
outFile.close();
} else {
cout << "Unable to open file." << endl;
}
}
vector<Contact> loadContacts() {
vector<Contact> contacts;
ifstream inFile("directory.txt");
if (inFile.is_open()) {
string line;
while (getline(inFile, line)) {
size_t pos = line.find(',');
if (pos != string::npos) {
Contact contact;
contact.name = line.substr(0, pos);
contact.phoneNumber = line.substr(pos + 1);
contacts.push_back(contact);
}
}
inFile.close();
} else {
cout << "Unable to open file." << endl;
}
return contacts;
}
void searchContact(const string& name) {
vector<Contact> contacts = loadContacts();
bool found = false;
for (const auto& contact : contacts) {
if (contact.name == name) {
cout << "Name: " << contact.name << ", Phone Number: " << contact.phoneNumber << endl;
found = true;
break;
}
}
if (!found) {
cout << "Contact not found." << endl;
}
}
int main() {
int choice;
while (true) {
cout << "1. Add Contact" << endl;
cout << "2. Search Contact" << endl;
cout << "3. Exit" << endl;
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Ignore newline character left in the buffer
if (choice == 1) {
Contact contact;
cout << "Enter name: ";
getline(cin, contact.name);
cout << "Enter phone number: ";
getline(cin, contact.phoneNumber);
addContact(contact);
} else if (choice == 2) {
string name;
cout << "Enter name to search: ";
getline(cin, name);
searchContact(name);
} else if (choice == 3) {
break;
} else {
cout << "Invalid choice, please try again." << endl;
}
}
return 0;
}
OUTPUT:
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 1
Enter name: ram
Enter phone number: 9488399999
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 1
Enter name: raj
Enter phone number: 9129320101
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 1
Enter name: gowri
Enter phone number: 9222122931
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 2
Enter name to search: ram
Name: ram, Phone Number: 9488399999
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 2
Enter name to search: ravi
Contact not found.
1. Add Contact
2. Search Contact
3. Exit
Enter your choice: 3
Explanation:
- Contact Structure: Holds the contact's name and phone number.
- File Operations:
addContact
appends new contacts to the file.loadContacts
reads all contacts from the file into a vector.searchContact
searches for a contact by name and prints the result.
- Main Function: Provides a simple menu-driven interface for adding and searching contacts.