Question
10.18: Phone Number List
Write a program that has an array of at least 50 string objects that hold people’s names and phone numbers. The program then reads lines of text from a file named phonebook into the array.
The program should ask the user to enter a name or partial name to search for in the array. All entries in the array that match the string entered should be displayed-- thus there may be more than one entry displayed.
Prompts And Output Labels. The program prints the message "Enter a name or partial name to search for: " and then after the user enters a some input and hits return, the program skips a line, and prints the heading: "Here are the results of the search:", followed by each matched string in the array on a line by itself.
Input Validation. None.
Solution (Raezorane R.)
#include
#include
#include
using namespace std;
int main()
{
const int SIZE = 50;
string phoneDirectory[SIZE];
int size=0;
string name; //name to look for
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail()) {
getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();
// Get a name or partial name to search for.
cout << "Enter a name or partial name to search for: ";
getline(cin, name);
cout << "\nHere are the results of the search: " << endl;
int numberEntriesFound = 0;
for (int k = 0; k < size; k++)
{
if (phoneDirectory[k].find(name.data(), 0) < phoneDirectory[k].length())
{
numberEntriesFound ++;
cout << phoneDirectory[k] << endl;
}
}
if (numberEntriesFound == 0)
cout << "\nNo Entries were found for " << name;
return 0;
}
Answers for C++ Course using "Starting out with C++ : from control structures through objects" by Tony Gaddis. 7/8th ed. I used the Pearson myprogramminglab to complete the homework. Here are my solutions/answers for the exercises/labs so please use the test bank as a GUIDE if you're stuck. Let me know if you find a better solution to a problem or any of the programming challenges. Thanks in advance for your support! Send in missing programming challenges to cplusplus.answers@gmail.com
The three "includes at the top" are missing. The following will fix them:
ReplyDelete#include < iostream >
#include < fstream >
#include < string >
removes the spaces between the '<>'