Building a Simple Telephone Book Program in C++
When learning C++, one of the most effective ways to practice is by building simple, real-world applications. In this tutorial, we'll create a telephone book program that allows you to store and manage contacts. This project is ideal for getting familiar with structures, dynamic memory allocation, and basic I/O operations in C++.
Problem Statement
We want to create a program that:
- Prompts the user for the number of contacts to be added.
- Dynamically allocates memory for these contacts.
- Allows the user to input names and phone numbers.
- Displays all the entered contacts.
- Properly deallocates the allocated memory to avoid memory leaks.
Solution: The C++ Telephone Book Program
#include <iostream>
#include <string>
using namespace std;
struct Telephone {
string name;
int number;
};
int main() {
int n;
cout << "How many contacts do you want to add? : ";
cin >> n;
Telephone *contacts = new Telephone[n];
cout << "\nEnter the details for each contact: \n";
for (int i = 0; i < n; i++) {
cout << "\nContact " << i + 1 << ":\n";
cout << "Name: ";
cin >> contacts[i].name;
cout << "Phone Number: ";
cin >> contacts[i].number;
}
cout << "\n--- Phonebook Details ---\n";
for (int i = 0; i < n; i++) {
cout << i + 1 << ") Name: " << contacts[i].name
<< ", Phone Number: " << contacts[i].number << "\n";
}
delete[] contacts;
return 0;
}
Understanding the Code
Let's break down the code and explain the core concepts:
1. Header Files
We include two essential headers:
- <iostream>: Handles input and output operations.
- <string>: Provides the string class, allowing us to store and manipulate text (names in this case).
2. Dynamic Memory Allocation
Memory allocation is crucial for flexibility. Instead of declaring a static array, we use new to dynamically allocate an array based on the number of contacts specified by the user.
Sign up here with your email
ConversionConversion EmoticonEmoticon