fork download
  1. //Maxwell Brewer CS1A Chapter 10, p. 592, #18
  2. //
  3. /*******************************************************************************
  4.  * PHONEBOOK SEARCH PROGRAM
  5.  * _____________________________________________________________________________
  6.  * This program allows the user to search for a name in a predefined phonebook.
  7.  * The user provides an input string, and the program displays all entries
  8.  * from the phonebook that contain the input as a substring (case-sensitive).
  9.  *
  10.  * INPUT:
  11.  * - A name or partial name entered by the user (max 20 characters).
  12.  *
  13.  * OUTPUT:
  14.  * - A list of phonebook entries matching the input string.
  15.  *******************************************************************************/
  16.  
  17. #include <iostream>
  18. #include <cstring>
  19. #include <string>
  20.  
  21. using namespace std;
  22.  
  23. // Function prototype
  24. void displayMatching(const string phonebook[], const char* searchTerm);
  25.  
  26. // Predefined phonebook data
  27. const string phonebook[11] = {
  28. "Alejandra Cruz, 555-1223",
  29. "Joe Looney, 555-0097",
  30. "Geri Palmer, 555-8787",
  31. "Li Chen, 555-1212",
  32. "Holly Gaddis, 555-8878",
  33. "Sam Wiggins, 555-0998",
  34. "Bob Kain, 555-8712",
  35. "Tim Haynes, 555-7676",
  36. "Warren Gaddis, 555-9037",
  37. "Jean James, 555-4939",
  38. "Ron Palmer, 555-2783"
  39. };
  40.  
  41. int main() {
  42. // Input buffer for the search term
  43. char searchTerm[21]; // 20 characters max + null terminator
  44.  
  45. // Prompt the user for input
  46. cout << "Enter a name or part of a name to search in the phonebook (max 20 characters): ";
  47. cin.getline(searchTerm, 21); // Read input up to 20 characters
  48.  
  49. cout << "\nMatching entries:\n";
  50. cout << "------------------\n";
  51.  
  52. // Call the function to display matching entries
  53. displayMatching(phonebook, searchTerm);
  54.  
  55. return 0; // Indicate successful program termination
  56. }
  57.  
  58.  
  59. void displayMatching(const string phonebook[], const char* searchTerm) {
  60. bool matchFound = false;
  61.  
  62. // Iterate through all entries in the phonebook
  63. for (int i = 0; i < 11; i++) {
  64. // Use strstr() to find if the input string is a substring of the current entry
  65. if (strstr(phonebook[i].c_str(), searchTerm)) {
  66. cout << phonebook[i] << endl; // Display the matching entry
  67. matchFound = true;
  68. }
  69. }
  70.  
  71. // If no match is found, inform the user
  72. if (!matchFound) {
  73. cout << "No matching entries found.\n";
  74. }
  75. }
Success #stdin #stdout 0.01s 5268KB
stdin
Joe Looney
stdout
Enter a name or part of a name to search in the phonebook (max 20 characters): 
Matching entries:
------------------
Joe Looney, 555-0097