|
| 1 | +//============================================================================ |
| 2 | +// Name : option.cpp |
| 3 | +// Author : TA's |
| 4 | +// Date : |
| 5 | +// Copyright : |
| 6 | +// Description : Command line processing for the sort program |
| 7 | +//============================================================================ |
| 8 | + |
| 9 | +#include <iostream> |
| 10 | +#include "option.h" |
| 11 | + |
| 12 | +/* initialize options according to command line */ |
| 13 | +void Option::init(int argc, char** argv) |
| 14 | + throw (InvalidArgument) |
| 15 | +{ |
| 16 | + // loop through all the arguments except for the program name itself |
| 17 | + for (int i = 1; i < argc; i++) |
| 18 | + { |
| 19 | + char* p = argv[i]; |
| 20 | + |
| 21 | + // if option does not start from dash, report an error |
| 22 | + if (*p != '-') throw InvalidArgument(); |
| 23 | + |
| 24 | + switch (p[1]) // switch on whatever comes after dash |
| 25 | + { |
| 26 | + case 'a': if (i+1 < argc) alg = argv[++i][0]; break; |
| 27 | + case 'f': if (i+1 < argc) input_file = argv[++i]; break; |
| 28 | + case 'o': if (i+1 < argc) output_file = argv[++i]; break; |
| 29 | + case 'h': show_help = true; break; |
| 30 | + case 'd': show_input = true; break; |
| 31 | + case 't': show_time = true; break; |
| 32 | + case 'c': show_num_cmps = true; break; |
| 33 | + case 'p': show_output = true; break; |
| 34 | + default : throw InvalidArgument(); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + if (!show_help && alg!='S' && alg!='B' && |
| 39 | + alg!='I' && alg!='H' && alg!= 'R') |
| 40 | + throw InvalidArgument(); |
| 41 | +} |
| 42 | + |
| 43 | + |
| 44 | +void Option::printUsage() const { |
| 45 | + std::cout << |
| 46 | + "Usage: ./sort [-a ALGORITHM] [-f INPUTFILE] [-o OUTPUTFILE] [-h] " |
| 47 | + "[-d] [-p] [-t] [-c]\n" |
| 48 | + "Read an integer sequence and display the sorted sequence, " |
| 49 | + "a program written by\n" |
| 50 | + "Author1, Author2 and Author3\n" |
| 51 | + "Example: ./sort -a S -f input.txt -o output.txt -t -c -p\n" |
| 52 | + " ./sort -h\n" |
| 53 | + "Options:\n" |
| 54 | + " -a ALGORITHM Use ALGORITHM to sort.\n" |
| 55 | + " ALGORITHM is a single character representing an algorithm:\n" |
| 56 | + " S (selection sort)\n" |
| 57 | + " B (bubble sort)\n" |
| 58 | + " I (insertion sort)\n" |
| 59 | + " H (shell sort)\n" |
| 60 | + " R (radix sort)\n" |
| 61 | + " -f INPUTFILE Obtain integers from INPUTFILE instead of STDIN\n" |
| 62 | + " -o OUTPUTFILE Place output message into OUTPUTFILE " |
| 63 | + "instead of STDOUT\n" |
| 64 | + " -h Display this help and exit\n" |
| 65 | + " -d Display input: unsorted integer sequence\n" |
| 66 | + " -p Display output: sorted integer sequence\n" |
| 67 | + " -t Display running time of the chosen algorithm in milliseconds\n" |
| 68 | + " -c Display number of element comparisons (excluding radix sort)\n"; |
| 69 | +} |
| 70 | + |
0 commit comments