Source of add_or_multiply.cpp


  1: //add_or_multiply.cpp
  2: //Adds or multiplies integers.

  4: #include <iostream>
  5: #include <string>
  6: #include <cstring>
  7: using namespace std;

  9: void DisplayUsage();
 10: /**<
 11: Display information on program usage.
 12: @return void
 13: @pre  None.
 14: @post Information on program usage has been displayed.
 15: */


 18: int main(int argc, char* argv[])
 19: {
 20:     if (argc == 1)
 21:     {
 22:         DisplayUsage();
 23:         cout << "Press Enter to continue ... ";  cin.ignore(80, '\n');
 24:         return 1;
 25:     }

 27:     if (strlen(argv[1]) != 1  ||
 28:         (argv[1][0] != '+'  &&  argv[1][0] != '*'))
 29:     {
 30:         cout << "\nError: Bad first parameter (must be + or *)."
 31:             "\nProgram now terminating.\n\n";
 32:         return 2;
 33:     }

 35:     int i;
 36:     int result;
 37:     switch (argv[1][0])
 38:     {
 39:     case '+':
 40:         result = 0;
 41:         for (i=2; i<argc; i++) result += atoi(argv[i]);
 42:         cout << "sum = ";
 43:         break;
 44:     case '*':
 45:         result = 1;
 46:         for (i=2; i<argc; i++) result *= atoi(argv[i]);
 47:         cout << "product = ";
 48:         break;
 49:     }
 50:     cout << result << endl;
 51: }


 54: void DisplayUsage()
 55: {
 56:     string blankLinesBefore(15, '\n');
 57:     string blankLinesAfter(5, '\n');
 58:     cout << blankLinesBefore
 59:         << "\nThis program requires two or more parameters. "
 60:         "\nThe first parameter must be a + sign or a * sign."
 61:         "\nEach subsequent parameter must be an integer."
 62:         "\nThe program then computes and displays the sum or "
 63:         "\nproduct of the integer values, as appropriate.\n"
 64:         "\nTypical usage:"
 65:         "\n\nprompt> add_or_multipy + 3 9 -4 12 17 -13 -18 2"
 66:         "\nsum = 8"
 67:         "\n\nprompt> add_or_multiply + 5"
 68:         "\nsum = 5"
 69:         "\n\nprompt> add_or_multiply * 12 3 2"
 70:         "\nproduct = 72"
 71:         "\n\nprompt> add_or_multiply * 27"
 72:         "\nproduct = 27"
 73:         << blankLinesAfter;
 74: }