Please fill out the skeleton of this code in order to take in text and count the
ID: 3749762 • Letter: P
Question
Please fill out the skeleton of this code in order to take in text and count the unique words with a few intermediate steps. #include <iostream> #include <iomanip> #include <fstream> using namespace std; struct WordCount { char word[31]; int count; }; // Function prototypes int countWords(const char*, WordCount[]); void stripPunctuation(char*); void stringToUpper(char*); int searchForWord(const char*, const WordCount[], int); void sortWords(WordCount[], int); void printWords(const WordCount[], int); int main(int argc, char* argv[]) { WordCount wordArray[200]; int numWords = 0; if (argc == 1) { cout << "Usage: assign1 [file-name] "; exit(1); } numWords = countWords(argv[1], wordArray); sortWords(wordArray, numWords); printWords(wordArray, numWords); return 0; } int countWords(const char* fileName, WordCount wordArray[]) { char word[31]; int numWords = 0; ifstream inFile(fileName); if (!inFile) { cout << "Error: unable to open " << fileName << endl; exit(1); } // Read and count the words while (inFile >> word) { } inFile.close(); return numWords; } void stripPunctuation(char* s) { } void stringToUpper(char* s) { } int searchForWord(const char* word, const WordCount wordArray[], int numWords) { return -1; } void sortWords(WordCount wordArray[], int numWords) { } void printWords(const WordCount wordArray[], int numWords) { }
Explanation / Answer
You want to know the number of unique word. So, for that you have to change the below code:
Within the loop you have to write as below:
Sample code:
for(int i =0; i<numWords; i++)
{
wordArray[i].count = 1;
}
for(int i =0 ; i < numWords; i++)
{
for(int j=i+1; j<numWords; j++)
{
if(strcmp(wordArray[i], wordArray[j] == 0)
{
wordArray[i].count = wordArray[j].count = 0;
}
}
}
int iNumberOfUniqueWord = 0;
for(int i =0; i<numWords; i++)
{
if (wordArray[i].count == 1)
{
iNumberOfUniqueWord++;
}
}
cout << iNumberOfUniqueWord;
Here you will get tthe number of unique word.from the variable "iNumberOfUniqueWord".
Explanation of logic :
Please check the code. Try and let us know if you face any logical issue regarding this code. Thanks.