A phonebook application in C++ that allows users to insert, delete, or alter contacts.
The code is for a basic phonebook application.
1. *Includes*:
- ``: For input/output functionalities.
- ``: Allows use of the `std::vector` dynamic array.
- ``: For string operations and management.
2. *Struct `Contact`*:
- Defines a contact with two members: `name` and `phoneNumber`, both of type `std::string`.
3. *Class `Phonebook`*:
- *Private Member*:
- `contacts`: A vector that stores all the contacts.
- *Public Methods*:
- `addContact()`: Adds a contact to the `contacts` vector.
- `displayContacts()`: Iterates over the `contacts` vector and displays each contact's name and phone number.
- `removeContact()`: Searches for a contact by name and if found, removes it. Returns `true` if successful, otherwise `false`.
- `searchContact()`: Searches for a contact by name. If found, returns a pointer to the contact; otherwise returns `nullptr`.
4. *Main Function (main())*:
The main() function serves as the driver function. It provides a user interface where users can choose different operations like adding, displaying, searching, and removing contacts from the phonebook. The operations loop until the user chooses to exit.
- *Initialization*:
- `Phonebook phonebook`: An instance of the `Phonebook` class.
- `int choice`: To store the user's menu choice.
- *Menu Loop*:
- A loop that displays a menu to the user until they choose to exit (option 5).
- Options include adding, displaying, searching for, and removing a contact.
- Each option has its case within the `switch` statement:
1. *Add Contact*: Takes the user's input for name and phone number and adds the contact.
2. *Display All Contacts*: Uses the `displayContacts()` method to display all the contacts.
3. *Search Contact*: Prompts the user to enter a name, then searches for that contact and displays it if found.
4. *Remove Contact*: Prompts the user to enter a name, then attempts to remove that contact. Indicates success or failure based on the return value.
5. *Exit*: Exits the loop and subsequently the program.
- Any other input gives an "Invalid choice" message.
5. *Buffer Clearing*:
- After reading an integer choice with `std::cin`, there's a need to clear the input buffer using `std::cin.ignore()` before reading strings. This prevents `getline` from immediately reading the leftover newline character.
6. *Looping Condition*:
- The `do-while` loop will continue to display the menu and execute the user's choices until the user selects the "Exit" option (5).
The program ends by returning `0`, indicating successful execution.
In summary, the code describes a simple phonebook application that allows users to perform basic operations on contacts like adding, displaying, searching by name, and removing by name.
Submitted by Abhishek Gupta (abhishekgupta02)
Download packets of source code on Coders Packet
Comments