Declare a structure telerec in C++, containing name (20 characters) and telephone number. Write a program to maintain a file of telephone records. The program should allow the following functions on the file:
1) To append records in the file.
2) Display the name for a given telephone number. If the telephone number does not exist then display error message "record not found".
3) Display the telephone number(s) for a given name. If the name does not exist then display error message "record not found".
1
Expert's answer
2018-08-24T10:42:08-0400
#include <iostream> #include <fstream> #include <string> using namespace std;
string phones = findPhonesByName(name); if (!phones.empty()) cout << "Phone(s):" << phones << endl; else cout << "record not found" << endl; cout << endl; } else if (option == FIND_NAME_BY_PHONE) { char phone[telerec::PHONE_SIZE]; cout << "Enter phone: "; cin.getline(phone, telerec::PHONE_SIZE); string name = findNameByPhone(phone); if (!name.empty()) cout << "Name: " << name << endl; else cout << "record not found" << endl; cout << endl; } }
return 0; }
// Write record to binary file void write(telerec& rec) { ofstream out(FILENAME, ios::binary | ios::app); out.write((char*)&rec, sizeof(rec)); }
// Returns phone(s) or empty string if not found string findPhonesByName(string name) { ifstream in(FILENAME, ios::binary); telerec rec; string phones; while (in.read((char*)&rec, sizeof(rec))) { if (name == rec.name) { phones += " "; phones += rec.phone; } } return phones; }
// Returns name or empty string if not found string findNameByPhone(string phone) { ifstream in(FILENAME, ios::binary); telerec rec; while (in.read((char*)&rec, sizeof(rec))) { if (phone == rec.phone) return rec.name; } return ""; }
Comments
Leave a comment