// // Program: phonebook. // // Purpose: look up names in "phone book". // // Input (from standard input): // Name of "phone book" file, a text file in which each line // contains two strings, a name and a phone number. // Name to look up. // Output (to standard output): // If phone book file contains a line matching the name to // look up, the corresponding phone number; otherwise, an // error message. #include #include #include // has exit(), EXIT_* #include // has setw() #include // has strcmp() // Function to obtain text string from user. // Pre: "prompt" contains text with which to prompt user. // "buffsz" is the size of array "buff". // Post: user has been prompted, and response is in "buff". // (Note that array parameters are always passed by reference.) void obtainString(char prompt[], char buff[], int buffsz) { cout << "Please enter " << prompt << ": "; cin >> setw(buffsz) >> buff; return; } // Main program. int main(void) { const int BUFFSIZE = 1000; char filename[BUFFSIZE]; // Obtain name of phone book file. obtainString("name of phone book file", filename, BUFFSIZE); // Open file. ifstream phonebook; phonebook.open(filename); if (!phonebook) { cout << "Unable to open " << filename << endl; exit(EXIT_FAILURE); } char nameToLookUp[BUFFSIZE]; obtainString("name to look up", nameToLookUp, BUFFSIZE); char name[BUFFSIZE]; char phone[BUFFSIZE]; while ((phonebook >> setw(BUFFSIZE) >> name >> setw(BUFFSIZE) >> phone) && (strcmp(name, nameToLookUp) != 0)); if (phonebook.eof()) cout << nameToLookUp << " not found.\n"; else cout << "The number is " << phone << ".\n"; phonebook.close(); return EXIT_SUCCESS; }