Advertisement
Taraxacum

WordsCounter

Oct 24th, 2018
349
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. #include <cstring>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5.  
  6. #define MAX_WORDS_UNIQUE 255
  7. #define WORD_MAX 80
  8.  
  9. #define isUpper(ch) ((ch) >= 'A' && (ch) <= 'Z')
  10. #define isLower(ch) ((ch) >= 'a' && (ch) <= 'z')
  11.  
  12. bool isAlpha(char ch)
  13. {
  14.     return isUpper(ch) || isLower(ch) || ch == '\'';
  15. }
  16.  
  17. char toUpper(char ch)
  18. {
  19.     return isLower(ch) ? ch - 'a' + 'A' : ch;
  20. }
  21.  
  22. char toLower(char ch)
  23. {
  24.     return isUpper(ch) ? ch - 'A' + 'a' : ch;
  25. }
  26.  
  27. void get_word(char* buffer, int size)
  28. {
  29.     int ptr = 0;
  30.     char ch;
  31.     while (cin.get(ch)) {
  32.         if (isAlpha(ch)) {
  33.             buffer[ptr++] = toLower(ch);
  34.         } else if (ptr > 0) {
  35.             buffer[ptr++] = '\0';
  36.             return;
  37.         }
  38.     }
  39. }
  40.  
  41. int main()
  42. {
  43.     freopen("in.txt", "r", stdin);
  44.  
  45.     char words[MAX_WORDS_UNIQUE][WORD_MAX] = { 0 };
  46.     int cnt[MAX_WORDS_UNIQUE] = { 0 };
  47.     char buffer[WORD_MAX] = { 0 };
  48.  
  49.     while (cin) {
  50.  
  51.         get_word(buffer, WORD_MAX);
  52.  
  53.         int idx = 0;
  54.         while (words[idx][0] != '\0' && idx < MAX_WORDS_UNIQUE) {
  55.             if (strcmp(buffer, words[idx]) == 0) {
  56.                 cnt[idx]++;
  57.                 break;
  58.             } else {
  59.                 idx++;
  60.             }
  61.         }
  62.  
  63.         if (idx < MAX_WORDS_UNIQUE && words[idx][0] == '\0') {
  64.             strcpy(words[idx], buffer);
  65.             cnt[idx]++;
  66.         }
  67.  
  68.         buffer[0] = '\0';
  69.     }
  70.  
  71.     for (int i = 0; i < MAX_WORDS_UNIQUE; i++) {
  72.         if (words[i][0]) {
  73.             cout << words[i] << "\t" << cnt[i] << endl;
  74.         }
  75.     }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement