Output of this code? Put in necessary header files, please! const int MAX_ENTRIE
ID: 3915095 • Letter: O
Question
Output of this code? Put in necessary header files, please!
const int MAX_ENTRIES = 20;
const int MAX_NAME_LEN = 40;
const int PHONE_LEN = 8;
struct PhoneEntry
{
char name[MAX_NAME_LEN + 1], phone[PHONE_LEN + 1];
};
struct PhoneBookType
{
int numPhones;
PhoneEntry phoneList[MAX_ENTRIES];
};
void ReadPhoneBook(PhoneBookType& APhoneBook);
void ReadEntry(PhoneEntry &entry);
void PrintMatches(const char number[], const PhoneBookType& APhoneBook);
void PrintEntry(const PhoneEntry &entry);
int main()
{
PhoneBookType MyPhoneBook;
char phoneNumber[PHONE_LEN + 1];
ReadPhoneBook(MyPhoneBook);
cout << endl;
cin >> phoneNumber;
while ( cin )
{
PrintMatches(phoneNumber, MyPhoneBook);
cout << endl;
cin >> phoneNumber;
}
return 0;
}
void ReadEntry(PhoneEntry &entry)
{
cin >> entry.phone;
cin >> entry.name;
}
void ReadPhoneBook(PhoneBookType& APhoneBook)
{
cout << "Number of entries in phone book: ";
cin >> APhoneBook.numPhones;
cout << "Enter items in the format " << endl;
for(int i = 0; i < APhoneBook.numPhones; i++)
ReadEntry(APhoneBook.phoneList[i]);
}
void PrintEntry(const PhoneEntry& entry)
{
cout << entry.name << ": " << entry.phone;
}
void PrintMatches(const char number[], const PhoneBookType& APhoneBook)
{
bool foundMatch = false;
cout << "Entries matching " << number << ":" << endl;
for(int i = 0; i < APhoneBook.numPhones; i++)
{
if ( strcmp(APhoneBook.phoneList[i].phone, number) == 0)
{
foundMatch = true;
PrintEntry(APhoneBook.phoneList[i]);
cout << endl;
}
}
if ( !foundMatch )
cout << "-- none" << endl;
}
Explanation / Answer
Hi! The output of this code will depend on how you execute it
Case 1
You execute the program and redirect the input stream to read from a file. If the contents of the file are as follows -
3
123456 Adam
123457 Bill
123458 Chad
123456
123457
123123
123458
First, the program asks for the number of entries which is 3
It then reads 3 entries in the form of <number> <name> (not that name cannot have spaces)
And then it reads each number following 3 entries and searches for those numbers in the address book
So the output for this case is
Number of entries in phone book: 3
Enter items in the format
123456 Adam
123457 Bill
123458 Chad
123456
Entries matching 123456:
Adam: 123456
123457
Entries matching 123457:
Bill: 123457
123123
Entries matching 123123:
-- none
123458
Entries matching 123458:
Chad: 123458
Case 2
In this case, the program won't terminate unless explicitly interrupted. It will keep waiting for phone numbers to search in the directory
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.