Write a simple telephone directory program in C++ that looks up phone numbers in a file containing a list of names and phone numbers. The user should be prompted to enter a first name and last name, and the program then outputs the corresponding number, or indicates that the name isn't in the directory. After each lookup, the program should ask the user whether they want to look up another number, and then either repeat the process or exit the program. The data on the file should be organized so that each line contains a first name, a last name, and a phone number, separated by blanks. You can return to the beginning of the file by closing it an opening it again.
// Array of product descriptions
char phoneDirectory[SIZE];
char name; // For user input
char *strPtr = NULL; // Result from strstr
ifstream inFile;
inFile.open("phonebook");
while (!inFile.fail())
{
cin.getline(inFile,phoneDirectory[size]);
size++;
}
inFile.close();
// Get user input
cout << "Enter a name to search for: ";
cin.getline(name, SIZE);
// Search for the string
int index = 0;
while(index < size)
{
strPtr = strstr(phoneDirectory[index], name);
if (strPtr != NULL)
break;
index++;
}
// Output the result of the search
if (strPtr == NULL)
cout << "No matching names were found.\n";
else
cout << phoneDirectory[index] << endl;
return 0;
}
I cant seem to fix the cin.getline's and the strstr.
You have declared name to be a single character. You want a string.
Get this code working and then consider what happens if the phonebook contains more than 50 entries. A more reliable way to do this program is to prompt for the name and then read the file. Compare each line of the file to the name and then throw it away if it doesn't match.
Since you will have to loop and do the whole lookup several times, consider putting it in a function. For now your main() can just call the function once. When you have it working, add the code to call the function inside a loop.