Question: 1) Explain and fix the logical flow bug within the switch statement. (What happens when the -h option is used?) 2) Explain and fix the
1) Explain and fix the logical flow bug within the switch statement. (What happens when the -h option is used?)
2) Explain and fix the argument parsing error. (Why is entrycount never zero?)
3) Fix print_result() to print results correctly and in the same order as the words were specified on the command line. Explain your solution.
/*
About this program: - This program counts words. - The specific words that will be counted are passed in as command-line arguments. - The program reads words (one word per line) from standard input until EOF or an input line starting with a dot '.' - The program prints out a summary of the number of times each word has appeared. - Various command-line options alter the behavior of the program. E.g., count the number of times 'cat', 'nap' or 'dog' appears. > ./main cat nap dog Given input: cat . Expected output: Looking for 3 words Result: cat:1 nap:0 dog:0 */ #include
#include
printf("Result: "); while (i < entry_count) { printf("%s:%d ", entries[i].word, entries[i].counter); i++; } } void printHelp(const char *name) { printf("usage: %s [-h] ... ", name); } int main(int argc, char **argv) { const char *prog_name = *argv; WordCountEntry entries[5]; int entryCount = 0; /* Entry point for the testrunner program */ if (argc > 1 && !strcmp(argv[1], "-test")) { run_smp0_tests(argc - 1, argv + 1); return EXIT_SUCCESS; }
argv++; while (*argv != NULL) { if (**argv == '-') { switch ((*argv)[1]) { case 'h': printHelp(prog_name); break; default: printf("%s: Invalid option %s. Use -h for help. ", prog_name, *argv); } } else{ if (entryCount < LENGTH(entries)) { entries[entryCount].word = *argv; entries[entryCount++].counter = 0; } } argv++; } // end while if (entryCount == 0) { printf("%s: Please supply at least one word. Use -h for help. ", prog_name); return EXIT_FAILURE; } if (entryCount == 1) { printf("Looking for a single word "); } else { printf("Looking for %d words ", entryCount); } process_stream(entries, entryCount); print_result(entries, entryCount); return EXIT_SUCCESS; }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
