1. Engineering
  2. Computer Science
  3. can you please split this program into h and cpp...

Question: can you please split this program into h and cpp...

Question details

can you please split this program into .h and .cpp file

#include <iostream>
#include<string>
#include<fstream>
#define SIZE 100
using namespace std;

//declare struct
struct word_block {
   std::string word;
   int count;
};
int getIndex(word_block arr[], int n, string s);

int main(int argc, char **argv)
{
   string filename="input.txt";
   //declare array of struct word_block
   word_block arr[SIZE];
   int count = 0;

   if (argc < 2)
   {
       cout << "Usage: " << argv[0] << " inputfilename" << endl;
       return -1;
   }

   //filename = argv[1];
   //cout << filename << endl;
   //open file for reading
   ifstream in;
   in.open(filename);
   //check if file can be opened
   if (!in)
   {
       cout << "Not able to open the input file " << filename << endl;
       return -1;
   }
   //read file till EOF
   string str;
   int i;

   while (!in.eof())
   {
       in >> str;
      
       //check if the word is presernt in the array of struct
      
       if ((i = getIndex(arr, count, str)) >= 0)
       {
           ++arr[i].count;
       }
       else
       {
           arr[count].word = str;
           arr[count].count = 1;
           ++count;
       }
      
   }
  
   word_block tmp;
   //sort the array in descending order of word count using bubble sort
   for (int i = 0; i < count; i++)
   {
       for (int j = 0; j < count - i - 1; j++)
       {
           if (arr[j].count < arr[j + 1].count)
           {
               tmp = arr[j + 1];
               arr[j + 1]= arr[j];
               arr[j] = tmp;

           }
       }
   }
   //print the output
   for (int i = 0; i < count; i++)
   {
       cout << arr[i].word << " appears " << arr[i].count << " times" << endl;
   }
   return 0;
}

int getIndex(word_block arr[], int n, string s)
{
   for (int i = 0; i < n; i++)
   {
       if (arr[i].word == s)
       {
           return i;
       }
   }
   return -1;
}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution