sayings2.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // sayings2.cpp -- using pointers to objects
  2. // compile with string1.cpp
  3. #include <iostream>
  4. #include <cstdlib> // (or stdlib.h) for rand(), srand()
  5. #include <ctime> // (or time.h) for time()
  6. #include "string1.h"
  7. const int ArSize = 10;
  8. const int MaxLen = 81;
  9. int main()
  10. {
  11. using namespace std;
  12. String name;
  13. cout <<"Hi, what's your name?\n>> ";
  14. cin >> name;
  15. cout << name << ", please enter up to " << ArSize
  16. << " short sayings <empty line to quit>:\n";
  17. String sayings[ArSize];
  18. char temp[MaxLen]; // temporary string storage
  19. int i;
  20. for (i = 0; i < ArSize; i++)
  21. {
  22. cout << i+1 << ": ";
  23. cin.get(temp, MaxLen);
  24. while (cin && cin.get() != '\n')
  25. continue;
  26. if (!cin || temp[0] == '\0') // empty line?
  27. break; // i not incremented
  28. else
  29. sayings[i] = temp; // overloaded assignment
  30. }
  31. int total = i; // total # of lines read
  32. if (total > 0)
  33. {
  34. cout << "Here are your sayings:\n";
  35. for (i = 0; i < total; i++)
  36. cout << sayings[i] << "\n";
  37. // use pointers to keep track of shortest, first strings
  38. String * shortest = &sayings[0]; // initialize to first object
  39. String * first = &sayings[0];
  40. for (i = 1; i < total; i++)
  41. {
  42. if (sayings[i].length() < shortest->length())
  43. shortest = &sayings[i];
  44. if (sayings[i] < *first) // compare values
  45. first = &sayings[i]; // assign address
  46. }
  47. cout << "Shortest saying:\n" << * shortest << endl;
  48. cout << "First alphabetically:\n" << * first << endl;
  49. srand(time(0));
  50. int choice = rand() % total; // pick index at random
  51. // use new to create, initialize new String object
  52. String * favorite = new String(sayings[choice]);
  53. cout << "My favorite saying:\n" << *favorite << endl;
  54. delete favorite;
  55. }
  56. else
  57. cout << "Not much to say, eh?\n";
  58. cout << "Bye.\n";
  59. // keep window open
  60. /* if (!cin)
  61. cin.clear();
  62. while (cin.get() != '\n')
  63. continue;
  64. cin.get();
  65. */
  66. return 0;
  67. }