-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphonebook.cpp
More file actions
104 lines (91 loc) · 2.85 KB
/
phonebook.cpp
File metadata and controls
104 lines (91 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
// Structure to store contact details
struct Contact {
string name;
string phone;
};
vector<Contact> phonebook;
// Function to add a contact
void addContact() {
Contact newContact;
cout << "Enter Name: ";
cin.ignore();
getline(cin, newContact.name);
cout << "Enter Phone Number: ";
cin >> newContact.phone;
phonebook.push_back(newContact);
sort(phonebook.begin(), phonebook.end(), [](const Contact &a, const Contact &b) {
return a.name < b.name;
});
cout << "Contact added successfully!\n";
}
// Function to display all contacts
void displayContacts() {
if (phonebook.empty()) {
cout << "Phonebook is empty!\n";
return;
}
cout << "\nContacts List:\n";
for (size_t i = 0; i < phonebook.size(); i++) {
cout << i + 1 << ". Name: " << phonebook[i].name << ", Phone: " << phonebook[i].phone << "\n";
}
}
// Function to search for a contact
void searchContact() {
string query;
cout << "Enter name or phone number to search: ";
cin.ignore();
getline(cin, query);
auto it = find_if(phonebook.begin(), phonebook.end(), [&query](const Contact &c) {
return c.name == query || c.phone == query;
});
if (it != phonebook.end()) {
cout << "Found: Name: " << it->name << ", Phone: " << it->phone << "\n";
} else {
cout << "Contact not found!\n";
}
}
// Function to delete a contact
void deleteContact() {
string name;
cout << "Enter the name of the contact to delete: ";
cin.ignore();
getline(cin, name);
auto it = remove_if(phonebook.begin(), phonebook.end(), [&name](const Contact &c) {
return c.name == name;
});
if (it != phonebook.end()) {
phonebook.erase(it, phonebook.end());
cout << "Contact deleted successfully!\n";
} else {
cout << "Contact not found!\n";
}
}
// Main function to run the menu
int main() {
int choice;
do {
cout << "\nPhonebook Management System\n";
cout << "1. Add Contact\n";
cout << "2. Display Contacts\n";
cout << "3. Search Contact\n";
cout << "4. Delete Contact\n";
cout << "5. Exit\n";
cout << "Enter your choice: ";
cin >> choice;
cin.ignore(); // Prevent issues with getline
switch (choice) {
case 1: addContact(); break;
case 2: displayContacts(); break;
case 3: searchContact(); break;
case 4: deleteContact(); break;
case 5: cout << "Exiting...\n"; break;
default: cout << "Invalid choice! Try again.\n";
}
} while (choice != 5);
return 0;
}