Tags:
create new tag
view all tags

Word Count - using Vectors, Strings, and Classes

WordCount.h

#include <string>

using namespace std;
#ifndef WORDCOUNT_H
#define WORDCOUNT_H
class WordCount {
private:
    string word;
    int count;
public:
    WordCount ();
    WordCount(string W);
    void inc();
    int getCount();
    string getWord();
};

WordCount.cpp

#include "WordCount.h"
    WordCount::WordCount (){
        word = "";
        count = 0;
    }
    WordCount::WordCount(string w){
        word = w;
        count = 1;
    }
    void WordCount::inc() {
        count++;
    }
    int WordCount::getCount(){
        return count;
    }
    string WordCount::getWord(){
        return word;
    }

main.cpp

#include <iostream>
#include <sstream>
#include <string>
#include "WordCount.h"
#include <vector>
using namespace std;
// Return index if found, otherwize -1
int findWord(vector<WordCount> words, string word);
int main()
{
    vector<WordCount> words;
    string s;
    cout << "Enter string:";
    getline(cin,s);
    istringstream iss(s);

    do
    {
        string word;
        iss >> word;
        if (word.length()>0) {
            
            int index = findWord(words,word);
            if (index>=0) {
                words[index].inc();
            } else {
                WordCount w = WordCount(word);
                words.push_back(w);
            }
        }
    } while (iss);
    
    for (int i =0;i<words.size(); i++) {
        cout << words[i].getWord() << ":" << words[i].getCount() << endl;
    }
}

int findWord(vector<WordCount> words, string word){
    
    for (int i = 0;i<words.size(); i++) {
        if(word == words[i].getWord()) {
            return i;
        }
    }
    return -1;
}
Edit | Attach | Watch | Print version | History: r2 < r1 | Backlinks | Raw View | Raw edit | More topic actions
Topic revision: r2 - 2017-11-09 - JimSkon
 
This site is powered by the TWiki collaboration platform Powered by PerlCopyright © 2008-2018 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback