Pushok

task7

Jun 17th, 2014
494
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.38 KB | None | 0 0
  1. struct Word
  2. {
  3.     Word(){}
  4.  
  5.     Word(const std::string &str) :
  6.         word(str), count(1)
  7.     {
  8.     }
  9.  
  10.     std::string word;
  11.     int count;
  12. };
  13.  
  14. void Sort(Word arr[], int size)
  15. {
  16.     for (int i = 0; i < size - 1; ++i)
  17.     {
  18.         for (int j = size - 2; j >= i; --j)
  19.         {
  20.             if (arr[j].count < arr[j + 1].count)
  21.             {
  22.                 std::swap(arr[j], arr[j + 1]);
  23.             }
  24.         }
  25.     }
  26. }
  27.  
  28. size_t Find(const Word* arr, int n, const std::string& match)
  29. {
  30.     for(int i = 0; i < n; ++i)
  31.         if(arr[i].word == match)
  32.             return i;
  33.  
  34.     return -1;
  35. }
  36.  
  37. void main(void)
  38. {
  39.     Word arr[32];
  40.     std::string text;
  41.     int n = 0;
  42.     char buff[128];
  43.     FILE *f = fopen("file.txt", "r");
  44.     if (f != nullptr)
  45.     {
  46.         while (!feof(f))
  47.         {
  48.             fgets(buff, sizeof(buff), f);
  49.             text += buff;
  50.             text += " ";
  51.         }
  52.         fclose(f);
  53.        
  54.         char* ptr = strtok(const_cast<char*>(text.c_str()), " ,-.\n\r\t");
  55.         while (ptr != nullptr)
  56.         {
  57.             if (n < sizeof(arr) / sizeof(Word))
  58.             {
  59.                 if (Find(arr, n, ptr) == -1)
  60.                 {
  61.                     arr[n++] = Word(ptr);
  62.                 }
  63.                 else
  64.                 {
  65.                     arr[Find(arr, n, ptr)].count++;
  66.                 }
  67.  
  68.                 ptr = strtok(nullptr, " ,-.\n\r\t");
  69.             }
  70.         }
  71.  
  72.         Sort(arr, n);
  73.  
  74.         printf("%-20s | %s\n", "Word", "Quantity");
  75.         printf("-------------------------------\n");
  76.         for (int i = 0; i < n; ++i)
  77.             printf("%-20s | %d\n", arr[i].word.c_str(), arr[i].count);
  78.             //std::cout << arr[i].word << " = " << arr[i].count << "\n";
  79.     }
  80.  
  81.     getchar();
  82. }
Advertisement
Add Comment
Please, Sign In to add comment