Write a program which will keep track of names and phone num
Write a program which will keep track of names and phone numbers. The program will use one or more vectors. The program will use a loop. The loop will print the following menu for each cycle.
Enter one of the following:
A to add a new name and phone number
L to list the names and phone numbers, with line numbers
Q to quit
The user will enter a letter from the menu. If any invalid letter is entered, the program will display an error message and repeat the menu.
If the user enters “A”, the program will ask for the name (which may contain blanks). After the name is entered, the program will ask for the phone number (which may contain non-numeric characters). The names will be stored in ascending order. For example,
A
Enter the name
Neumann, Alfred E.
Enter the phone number
(405)555-0001
If the user enters “L”, the program will list all of the names and phone numbers. For example,
L
0 Dough, Jane (405)555-0003
1 Neumann, Alfred E. (405)555-0001
2 Xavier, Charles (800)987-6543
If the user enters “Q”, the program comes to a normal end.
Solution
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
//struct contact made of name and phone number
struct contact{
string name;
string phone;
};
//compare function to sort the vector
struct compare
{
inline bool operator() (const contact& struct1, const contact& struct2)
{
return (struct1.name < struct2.name);
}
};
//main method
int main(){
//declaring variables
char choice;
string name;
string phone;
vector <contact> contacts;
//run the loop till the user doesn\'t enter Q
while (choice!=\'Q\'){
//taking choice as an input
cout<<\"Enter one of the following:\ A to add a new name and phone number.\ L to list the names and phone numbers, with line numbers.\ Q to quit\"<<endl;
cin>>choice;
//if the user wants to add
if(choice==\'A\'){
//taking in name
cout<<\"Enter the name: \";
cin>>name;
//taking in phone
cout<<\"\ Enter the phone number: \";
cin>>phone;
cout<<endl;
//creating a contact object
contact con;
con.name = name;
con.phone = phone;
//adding the contact to the contacts vector
contacts.push_back(con);
//sorting the vector
sort(contacts.begin(), contacts.end(), compare());
}
//if user choses L, list the contacts
else if(choice==\'L\'){
//loop to print all the elements of the vector
for (int i=0; i<contacts.size(); i++){
cout<<i<<\" \"<<contacts[i].name<<\" \"<<contacts[i].phone<<endl;
}
}
}
return 0;
}

