Question

In: Computer Science

code in. c++ void seen ); If there is already a Word object in the Words...

code in. c++

void seen );
If there is already a Word object in the Words list, then the number of occurrences for this word is incremented. If there is no Word object for this word already, create a new word object with occurrence =1, and insert this object into the list of Word objects.

getNextWord();
Returns the next word of the list and sets the currentItem pointer to the next Word. This may return an empty string, “”, if the pointer is NULL.
StackNode* findWord(std::string);
Returns a pointer to some Word in the list. Return NULL if not found.

Write a driver to do the following:

Create a Words object. This is a linked list of Word objects.

Open an input file full of mixed words. Read each word. For each word in the input file, call the seen method for this word. The seen method takes a string argument. For example, the word ‘cat’ was just read in. Call myWords.seen(“cat”).

After processing all of the words in the file, close the file.

Last, print out the statistics of the file to the console. Include:
For every word in the Words object, print the word and the number of occurrences. The total number of Words in the file.

complete

#ifndef WORD_H_
#define WORD_H_
#include <string>;

class Word
{
private:
        std::string word;
        int occurrences;
public:
        Word(std::string w); //word = w and occurrences = 1
        std::string getWord() const; //return the stored word
        int getOccurrences() const;
        void increment();       //increment the occurrences value
};

#endif

complete

#ifndef WORDS_H_
#define WORDS_H_
#include <string>;
#include "Word.h";

class Words
{
        private:
                struct StackNode
                {
                        Word word;
                        StackNode *next;
                };

                StackNode *top;
                StackNode *currentItem;
                StackNode* findWord(std::string); //Returns a pointer to some Word in the list
                                                                                        // return NULL if not found
        public:
                Words() // Create an empty list of Word objects
                        {       top = NULL;
                                resetNextWord();
                        }
                void remove(std::string); //remove a word object, if it is in the list
                bool find(std::string) const; //if the word, as a string, is in the list, return true. else false
                void seen(std::string); //pass in a word, as a string, that has been seen.
                                                // If this word is not in the list, insert it with
                                                // the number of occurrences = 1.
                                                // If this word is in the list, increment the
                                                // occurrences for this word.
                int getOccurrences(std::string) const; //return the value of occurrences
                int getLength() const;          // returns the length of the list. NOT STORED
                std::string getNextWord();      // returns the next word of the list and sets
                                                                        // the currentItem pointer to the next Word
                void resetNextWord(); //resets the currentItem pointer to top.
                bool isEmpty() const;
};

#endif

Solutions

Expert Solution

Below is completed code. You need to use your own input file i have provided "input.txt" just for test for code.

Let me know if you have any problem or doubt. Thank you.

===================================================================

Word.h

========================

#ifndef WORD_H_
#define WORD_H_
#include <string>;

class Word
{
private:
    std::string word;
    int occurrences;
public:
    Word(std::string w); //word = w and occurrences = 1
    std::string getWord() const; //return the stored word
    int getOccurrences() const;
    void increment();       //increment the occurrences value
};

#endif

========================

Word.cpp

========================

#include "Word.h"

Word::Word(std::string w)
{
   word = w;
   occurrences = 1;
}

std::string Word::getWord() const
{
   return word;
}

int Word::getOccurrences() const
{
   return occurrences;
}

void Word::increment()
{
   occurrences++;
}

========================

Words.h

========================

#ifndef WORDS_H_
#define WORDS_H_
#include <string>;
#include "Word.h";

class Words
{
private:
    struct StackNode
    {
        Word word;
        StackNode* next;
        // constructor to add new nodes
        StackNode(std::string w) : word(w), next(NULL){}
    };

    StackNode* top;
    StackNode* currentItem;
    StackNode* findWord(std::string word)
    {
        // create iterator to loop over list
        StackNode* wordNode = top;
        while (wordNode != NULL)
        {
            // compare string to check for given word
            if (wordNode->word.getWord().compare(word) == 0)
            {
                // return current node
                return wordNode;
            }
        }
        return NULL;
    }
public:
    Words() // Create an empty list of Word objects
    {
        top = NULL;
        resetNextWord();
    }
    void remove(std::string); //remove a word object, if it is in the list
    bool find(std::string) const; //if the word, as a string, is in the list, return true. else false
    void seen(std::string); //pass in a word, as a string, that has been seen.
                                    // If this word is not in the list, insert it with
                                    // the number of occurrences = 1.
                                    // If this word is in the list, increment the
                                    // occurrences for this word.
    int getOccurrences(std::string) const; //return the value of occurrences
    int getLength() const;          // returns the length of the list. NOT STORED
    std::string getNextWord();      // returns the next word of the list and sets
                                                            // the currentItem pointer to the next Word
    void resetNextWord(); //resets the currentItem pointer to top.
    bool isEmpty() const;
};

#endif

========================

Words.cpp

========================

#include "Words.h"

void Words::remove(std::string word)
{
    // find node with given word
    StackNode* wordNode = findWord(word);
    // nothing to do if word is not in list
    if (wordNode != NULL)
    {
        // remove the word object from list

    }
}
bool Words::find(std::string word) const
{
    // if number of occurrence is 0 then word is not in list
    // if word is in list it must have occurrence more than 0
    return getOccurrences(word) > 0;
}

void Words::seen(std::string word)
{
    // find node with given word
    StackNode* wordNode = top;
    // create pointer to add node in list
    StackNode* previous = top;
    // check for empty list
    if (isEmpty()) {
        // add first node in list
        top = currentItem = new StackNode(word);
        return;
    }
    // create a loop to find the word
    while (wordNode != NULL)
    {
        // compare string to check if word already exist in list
        if (wordNode->word.getWord().compare(word) == 0)
        {
            // increase occurrence for already existing word
            wordNode->word.increment();
            // return to avoid adding same word at end of list
            return;
        }
        // move to next node
        previous = wordNode;
        wordNode = wordNode->next;
    }
    // if node with given word is not found then add new word at end of list
    previous->next = new StackNode(word);
}

int Words::getOccurrences(std::string word) const
{
    // find node with given word and return occurrences
    StackNode* wordNode = top;
    // create a loop to find the word
    while (wordNode != NULL)
    {
        // compare string to check for word
        if (wordNode->word.getWord().compare(word) == 0)
        {
            return wordNode->word.getOccurrences();
        }
        // move to next node
        wordNode = wordNode->next;
    }
    // if word is not in list then occurrence is 0
    return 0;
}

int Words::getLength() const
{
    // create an iterator to count number of words
    int num_words = 0;
    StackNode* itr = top;
    while (itr != NULL)
    {
        // count current word and move to next node
        num_words++;
        itr = itr->next;
    }
    return num_words;
}

std::string Words::getNextWord()
{
    // if next word is NULL return empty string
    if (currentItem == NULL)
    {
        return "";
    }
    else
    {
        std::string next = currentItem->word.getWord();
        currentItem = currentItem->next;
        return next;
    }
}

void Words::resetNextWord()
{
    currentItem = top;
}

bool Words::isEmpty() const
{
    // list is empty if top element is NULL
    return top == NULL;
}

========================

Main.cpp

========================

#include <iostream>
#include <fstream>
#include <iomanip>
#include "Words.h"

int main() {
   // ask user to input file name
   std::cout << "Enter input file name: ";
   std::string filename;
   std::cin >> filename;

   // create a Words list
   Words words;
   // open input file
   std::ifstream file(filename);
   // check for valid file name
   if (!file.is_open())
   {
       std::cerr << "Can not open input file: " << filename << std::endl;
       return 1;
   }

   // create a loop to read data from file
   std::string word;
   while (!file.eof()) {
       // read each word from file
       file >> word;
       // call seen function for each word
       words.seen(word);
   }

   // print statistics
   std::cout << std::left << std::setw(20) << "Word" << "Occurrences" << std::endl;
   std::cout << "===============================\n";
   int total_words = 0;
   int len = words.getLength();
   for (int i = 0; i < len; i++) {
       std::string w = words.getNextWord();
       int occurence = words.getOccurrences(w);
       std::cout << std::setw(25) << w << occurence << std::endl;
       total_words += occurence;
   }
   std::cout << "===============================\n";
   std::cout << std::setw(25) << "Total Words: " << total_words << std::endl;

   return 0;
}

========================

input.txt

========================

dog
cat
rat
fish
elephant
cat
fish
cow


Related Solutions

C++ Write the C++ code for a void function that prompts the user to enter a...
C++ Write the C++ code for a void function that prompts the user to enter a name, and then stores the user's response in the string variable whose address is passed to the function. Name the function getName.
C++ Please complete based on the code below. Declare another stack object to the code in...
C++ Please complete based on the code below. Declare another stack object to the code in main(). Add a stack operator called CopyStack to the Stack class which, when executed, copies the contents of the first stack into the second stack. Modify your menu so that this option is available. The menu should also allow the second stack to be printed, pushed, popped, and so forth, just like with the first stack. #include using namespace std; #define MAXSize 10 class...
Given the root C++ code: void sort() {    const int N = 10;    int...
Given the root C++ code: void sort() {    const int N = 10;    int x[N];    for(int i = 0; i < N; i++)    {        x[i] = 1 + gRandom-> Rndm() * 10;        cout<<x[i]<<" "; }    cout<<endl;    int t;       for(int i = 0; i < N; i++)    {    for(int j = i+1; j < N; j++)    {        if(x[j] < x[i])        {   ...
Why is my C code counter returning the wrong output? void removeLn(char *tPtr) { for (;...
Why is my C code counter returning the wrong output? void removeLn(char *tPtr) { for (; *tPtr != '\0'; tPtr++) { if (*tPtr == '\n') { *tPtr = '\0'; } } } This is a method I wrote that essentially replaces the \n in a text file with a null. int counter(FILE *filePtr) { char ln[length]; int counter = 0; while (fgets(ln, length, filePtr) != NULL) { char *r;    for (r = ln; *r != '\0';) { while (isspace(*r))...
C++ How to make this code take a class object instead of int for the vector...
C++ How to make this code take a class object instead of int for the vector queue and be able to enqueue and dequeue the object? #include <iostream> #include <float.h> #include <bits/stdc++.h> using namespace std; void print_queue(queue<int> Q) //This function is used to print queue { while (!Q.empty()) { cout<< Q.front() << " "; Q.pop(); } } int main() { int n = 10; vector< queue<int> > array_queues(n); //Create vector of queues of size 10, each entry has a queue...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare...
CODE: C# using System; public static class Lab6 { public static void Main() { // declare variables int hrsWrked; double ratePay, taxRate, grossPay, netPay=0; string lastName; // enter the employee's last name Console.Write("Enter the last name of the employee => "); lastName = Console.ReadLine(); // enter (and validate) the number of hours worked (positive number) do { Console.Write("Enter the number of hours worked (> 0) => "); hrsWrked = Convert.ToInt32(Console.ReadLine()); } while (hrsWrked < 0); // enter (and validate) the...
CODE IN C++ PLEASE Create a structure (object) named Person that has the following characteristics: •...
CODE IN C++ PLEASE Create a structure (object) named Person that has the following characteristics: • full name • age • family members full names represent by an array of size 10. Write a program that creates an array of Person of size 5. Populate the array of objects with the information given by user input according to the following specifications: • With input from the user i) Populate only 3 positions of the array of Person object. ii) Populate...
What must be the position of an object in order that it may be seen distinctly...
What must be the position of an object in order that it may be seen distinctly through a +9.0 D lens placed 2.9 cm in front of an eye, the eye being accommodated for a distance of 35.5 cm? Give your answer in cm as a distance to the lens.
*Answer in C program* Given a program as shown below: #include <stdio.h> void function1(void); void function2...
*Answer in C program* Given a program as shown below: #include <stdio.h> void function1(void); void function2 (int, double x); void main (void) { int m; double y; m=15; y=308.24; printf ("The value of m in main is m=%d\n\n",m); function1(); function2(m,y); printf ("The value of m is main still m = %d\n",m); } void function1(void) { printf("function1 is a void function that does not receive\n\\r values from main.\n\n"); } void function2(int n, double x) { int k,m; double z; k=2*n+2; m=5*n+37;...
C++ QUESTION ABOUT FIXING CODE AND RUNNING TESTS: class SpeakerSystem { public: void vibrateSpeakerCones(unsigned signal) const...
C++ QUESTION ABOUT FIXING CODE AND RUNNING TESTS: class SpeakerSystem { public: void vibrateSpeakerCones(unsigned signal) const { cout << "Playing: " << signal << "Hz sound..." << endl; cout << "Buzz, buzzy, buzzer, bzap!!!\n"; } }; class Amplifier { public: void attachSpeakers(const SpeakerSystem& spkrs) { if(attachedSpeakers) cout << "already have speakers attached!\n"; else attachedSpeakers = &spkrs; }    void detachSpeakers() { // should there be an "error" message if not attached? attachedSpeakers = nullptr; }    void playMusic( ) const...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT