CPP Telephone Book Program
#include <iostream>
#include <string>
using namespace std;
struct Telephone {
int number;
string name;
};
int main() {
int n;
cout << "\nHow many contacts do you want to add? : ";
cin >> n;
struct Telephone *t = new struct Telephone[n];
cout << "\nEnter the details to be filled in the Telephone book : \n";
for (int i = 0; i < n; i++) {
cout << "\nEnter name for contact " << i + 1 << " : ";
cin >> t[i].name;
cout << "Enter number for contact " << i + 1 << " : ";
cin >> t[i].number;
}
cout << "\nDetails in the Phonebook are : \n";
for (int i = 0; i < n; i++) {
cout << "\n\t" << i + 1 << ") Name: " << t[i].name << "\t" << i + 1 << ") Number: " << t[i].number;
}
delete[] t;
cout << endl;
return 0;
}
This C++ code creates a simple telephone book program where the user can add contacts with names and numbers. Let's break down the code step by step:
Header Files:
The code includes two standard C++ header files:
<iostream>
: This header file is for input and output operations.<string>
: This header file provides the string class to handle strings.
Namespace:
The using namespace std;
statement allows the program to use names from the std
namespace without prefixing them with std::
.
Structure Declaration:
A structure Telephone
is declared, which contains two members:
number
: An integer to store the telephone number.name
: A string to store the name associated with the telephone number.
Main Function:
The main()
function is where the execution of the program begins.
Variable Declaration:
int n;
: It declares an integer variable n
, which will store the number of contacts the user wants to add.
struct Telephone *t = new struct Telephone[n];
: It dynamically allocates memory for an array of Telephone structures based on the user input n
.
User Input:
The program prompts the user to enter the number of contacts they want to add (n
) and reads the input using cin
.
It then prompts the user to enter the details (name and number) for each contact and stores them in the array of Telephone structures.
Output:
After the user has entered all the contacts, the program displays the details of all the contacts entered by the user.
Deallocation:
delete[] t;
: It deallocates the dynamically allocated memory to avoid memory leaks.
Return:
The main()
function returns 0
, indicating successful execution of the program.
This code demonstrates the usage of structures, dynamic memory allocation, input/output operations, and loops in C++ to create a basic telephone book program.
Sign up here with your email
ConversionConversion EmoticonEmoticon