/****************************************************************************** * * Name : Scott Kristjanson * Number : 123456789 * email : skristja@sfu.ca * Course : Cmpt135 * Assmt : 1 * Question : B1 * * File : RandomAvg.cpp * * This implements the RandomAvg program for Assignment 1 Question B1. * This program accepts a command line parameter that specifies how many * random numbers to generate from 1 to 999. Each random number should be * between 1 and 100 inclusive. * * ******************************************************************************/ #include #include #include #include using namespace std; //////////////////////////////////////////////// // // Global variables. // //////////////////////////////////////////////// // The maximum number of random numbers to generate const int MaxRandoms = 999; // The Min and Max Values of Randoms that we want const int MaxRandom = 100; const int MinRandom = 1; // Error Codes const int ErrWrongNumberOfParms = -1; const int ErrInvalidParm = -2; const int ErrParmOutOfRange = -3; /****************************************************************************** * * Helper Functions * ================ * ******************************************************************************/ /****************************************************************************** * * DisplayUsage * ============ * Display how the program should be invoked via cout. * * Parameters: * char *cmdName // Name used to invoke this program * * Returns: * Nothing * ******************************************************************************/ void DisplayUsage(const char *cmdName) { string name(cmdName); // Converts C style char* to C++ style string object name = name.substr(name.find_last_of("/\\") + 1); // http://stackoverflow.com/questions/8520560/get-a-file-name-from-a-path cout << "Usage: " << name << " " << endl; cout << " Where num is between 1 and " << MaxRandoms << endl; } /***************************************************************************** * * HaveInt * ======= * Check if the string str contains an int. It skips over any leading white * space before checking for an optional sign character, following by one or * numeric digits. If these digits are found, and no non-space characters are * found past the end, then intVal is updated with the found int value, and true * is returned * * Note to Students: * There is no need to be this fancy for assignment #1. You could simply call * function stod(argv[1]) to convert the C string into a numeric value. I did * not use stod() in this example solution since it may cause an exception if * the value of str is non-numeric. We have not reviewed exception handling yet. * This would work provided str is a numeric string: * val=stod(str); * * Parameters: * str - a pointer to a character array that may contain an int value * intVal - a pointer to the intVal to update if an int is found. * * Returns: * true - if an int is found and returned in intVal * false - otherwise * ******************************************************************************/ bool HaveInt(const char *str, int& intVal) { bool isInt = false; // Set true if we find an int int neg = false; // Set true if starts with a '-' int val = 0; // Value of int (if found /* Skip past any whitespace */ while (isspace(*str)) str++; /* Check for negative numbers */ if (*str =='-') { // This starts with a - sign, remember that and skip over this char neg = true; str++; } else { // Just skip over an optional + sign if (*str == '+') str++; } /* If the next char is numeric, start reading in the int val */ if (isdigit(*str)) { isInt = true; while (isdigit(*str)) val = val*10 + (*str++ - '0'); /* Negate val if neg was set true */ if (neg) val *= -1; /* Check if any non-whitespace remain */ while (*str) if (!isspace(*str++)) isInt = false; } /* Update intVal is we found an int */ if (isInt) intVal = val; return isInt; } /****************************************************************************** * * ParseParms * ========== * The routine parses the commend line parameters. It is expected that this * program is invoked from the command line with exactly one command * line parameter: * RandomAvg * where is an positive int from 1 to 999 * * Side Effects: * If the number of parameters is not one (excluding the command name itself), * or if is not and int from 1 to 999, print the usage statement and this * routine exits the program with a non-zero error code. * ******************************************************************************/ int ParseParms(int argc, char **argv) { int numWanted; /* If the wrong number of parameters specified, display Usage and exit */ if (argc != 2) { DisplayUsage(argv[0]); exit(ErrWrongNumberOfParms); } // Exit it specified num is not numeric. // Note: No need to check for non-ints but this will get 1 bonus mark. // Ok to simply called stod(argv[1]) instead if (!HaveInt(argv[1], numWanted)) { DisplayUsage(argv[0]); exit(ErrInvalidParm); } /* If num specified is not between 1 and max, display usage and exit*/ if ((numWanted < 1) or (numWanted > MaxRandoms)) { DisplayUsage(argv[0]); exit(ErrParmOutOfRange); } return numWanted; } /****************************************************************************** * * Main function * ============= * Main expects to be invoked from the command line with exactly one command * line parameter: * RandomAvg * where is an positive int from 1 to 999 * * If the number of parameters is not one (excluding the command name itself), * or if is not and int from 1 to 999, print the usage statement. * * Note: if is not an int, it is ok for this program to crash. * ******************************************************************************/ int main(int argc, char **argv) { int numWanted = 0; int randNum = 0; int range = (MaxRandom - MinRandom) + 1; // Number of randoms in range int max = MinRandom; int min = MaxRandom; int sum = 0; double avg = 0; // Verify that the command line parameters are correct, exit if not valid. // Returns the number random numbers to generate. numWanted = ParseParms(argc, argv); /* Initialize the seed for the random number generator */ srand(time(0)); cout << "Your " << numWanted << " lucky numbers are:"; for(int i=0; i randNum) min = randNum; } cout << endl; // Compute the average avg = static_cast(sum)/numWanted; // Set up cout to display doubles with 3 decimal places cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(3); // Display the Stats about the Random numbers generated cout << "Largest = " << max << endl; cout << "Average = " << avg << endl; cout << "Smallest= " << min << endl; }