cppbeginner10 minutes

Simple Contact List Manager in C++

Create a basic contact list manager where users can add, display, and search contacts using console input and output.

Challenge prompt

Build a simple console application in C++ that manages a list of contacts. Each contact should have a name and a phone number. The program should allow users to: 1) Add a new contact, 2) Display all contacts, and 3) Search contacts by name and display matching results. Implement a simple menu loop to let the user choose these actions until they decide to exit.

Guidance

  • Use a struct or class to represent a contact with name and phone number fields.
  • Store contacts in a simple container such as a vector.
  • Use a loop to repeatedly show the menu and execute the selected operation.
  • Use basic string input/output and simple loops to display and search contacts.

Hints

  • Consider using std::vector to hold all your contacts for easy addition and iteration.
  • For searching, loop through the vector and compare contact names with the search input using string operations.

Starter code

#include <iostream>
#include <vector>
#include <string>

struct Contact {
    std::string name;
    std::string phone;
};

int main() {
    std::vector<Contact> contacts;
    int choice = 0;
    while (choice != 4) {
        std::cout << "Menu:\n1. Add Contact\n2. Display Contacts\n3. Search Contact\n4. Exit\nEnter choice: ";
        std::cin >> choice;
        std::cin.ignore(); // clear newline

        if (choice == 1) {
            // Add contact
        } else if (choice == 2) {
            // Display all contacts
        } else if (choice == 3) {
            // Search contacts
        } else if (choice == 4) {
            std::cout << "Exiting..." << std::endl;
        } else {
            std::cout << "Invalid choice. Try again." << std::endl;
        }
    }
    return 0;
}

Expected output

Menu: 1. Add Contact 2. Display Contacts 3. Search Contact 4. Exit Enter choice: 1 Enter name: Alice Enter phone: 12345 Menu: 1. Add Contact 2. Display Contacts 3. Search Contact 4. Exit Enter choice: 2 Contacts List: Name: Alice, Phone: 12345 Menu: 1. Add Contact 2. Display Contacts 3. Search Contact 4. Exit Enter choice: 3 Enter name to search: Alice Found: Name: Alice, Phone: 12345 Menu: 1. Add Contact 2. Display Contacts 3. Search Contact 4. Exit Enter choice: 4 Exiting...

Core concepts

structsvectorsloopsconditional statements

Challenge a Friend

Send this duel to someone else and see if they can solve it.