Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. > ./main cat nap dog
  2. Given input:
  3. cat
  4. .
  5. Expected output:
  6. Looking for 3 words
  7. Result:
  8. cat:1
  9. nap:0
  10. dog:0
  11.  
  12. #define LENGTH(s) (sizeof(s) / sizeof(*s))
  13.  
  14. /* Structures */
  15. typedef struct {
  16. char *word;
  17. int counter;
  18. } WordCountEntry;
  19.  
  20.  
  21. int process_stream(WordCountEntry entries[], int entry_count)
  22. {
  23. short line_count = 0;
  24. char buffer[30];
  25.  
  26. while (fgets(buffer,sizeof(buffer),stdin)) {
  27. if (*buffer == '.')
  28. break;
  29. /* Compare against each entry */
  30. int i = 0;
  31. while (i < entry_count) {
  32. if (!strcmp(entries[i].word, buffer))
  33. entries[i].counter++;
  34. i++;
  35. }
  36. line_count++;
  37. }
  38. return line_count;
  39. }
  40.  
  41.  
  42. void print_result(WordCountEntry entries[], int entry_count)
  43. {
  44. fprintf(stdout,"Result:n");
  45.  
  46. for(int i=0; i <=entry_count;i++){
  47. printf("%s:%dn", entries[i].word, entries[i].counter);
  48. }
  49. }
  50.  
  51.  
  52. void printHelp(const char *name)
  53. {
  54. fprintf(stderr,"usage: %s [-h] <word1> ... <wordN>n", name);
  55. }
  56.  
  57.  
  58. int main(int argc, char **argv)
  59. {
  60. const char *prog_name = *argv;
  61.  
  62. WordCountEntry entries[argc];
  63. int entryCount = 0;
  64.  
  65. while ((*argv) != NULL) {
  66. if (**argv == '-') {
  67.  
  68. switch ((*argv)[1]) {
  69. case 'h':
  70. printHelp(prog_name);
  71. break;
  72. case'f':
  73. freopen((*argv)[2],"w",stdout);
  74. break;
  75. default:
  76. fprintf(stderr,"%s: Invalid option %s. Use -h for help.n",
  77. prog_name, *argv);
  78. }
  79. } else {
  80. if (entryCount < argc-1) {
  81. entries[entryCount].word = *argv;
  82. entries[entryCount++].counter = 0;
  83.  
  84. }
  85. }
  86. argv++;
  87. }
  88. if (entryCount == 0) {
  89. fprintf(stderr,"%s: Please supply at least one word. Use -h for help.n",
  90. prog_name);
  91. return EXIT_FAILURE;
  92. }
  93. if (entryCount == 1) {
  94. fprintf(stdout,"Looking for a single wordn");
  95. } else {
  96. fprintf(stdout,"Looking for %d wordsn", entryCount);
  97. }
  98. process_stream(entries, entryCount);
  99. print_result(entries, entryCount);
  100.  
  101. return EXIT_SUCCESS;
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement