Write a c++ program to do the following: Reads in and prints a text, line by lin
ID: 3693871 • Letter: W
Question
Write a c++ program to do the following: Reads in and prints a text, line by line, and calls a series of functions. The main program calls a function : diffwords() to count the number of different words in the entire text (ignoring case). wordcount() to count the number of times each word appears in the text. printcount() to print a list of all the words in the text, together with the count of the number of times they appear. For example, if a word occurs twice in the text, it appears only once on the list, with a count of 2. Print the list of words in alphabetical order. Use other functions wherever appropriate. For example, suppose the text is this: The elephant ate the banana and the giraffe ate the banana. The function diffwords() produces a count of 6 ("the", "elephant", "ate", "banana", and "giraffe"); wordcount() produces this list: and 1 ate 2 banana 2 elephant 1 giraffe 1 the 4 Note: No Globle Variables
Explanation / Answer
#include <iostream>
#include <iomanip>
#include <sstream>
#include <map>
#include <cctype>
using namespace std;
void removePunct(string&);
void toLower(string&);
bool isApostrophe(const char);
int diffwords(const map<string,int>&);
int wordcount(const map<string,int>&);
void printcount(const map<string,int>&);
int main(int argc, char *argv[]) {
map<string,int> freq;
string file,line,word;
stringstream ss;
//
// Read lines from stdin and count word frequencies until EOF (Ctrl-d if
// running interactively, or input may be piped in from a file).
//
while (getline(cin,line)) {
ss.str(line);
while (ss.good()) {
if (ss >> word) {
removePunct(word);
toLower(word);
if (freq.find(word) == freq.end()) {
freq.insert(pair<string,int>(word,1));
} else {
freq[word]++;
}
}
}
ss.clear();
}
cout << "Number of different words: " << diffwords(freq) << endl;
printcount(freq);
return(0);
}
int diffwords(const map<string,int> &wordMap) {
return wordMap.size();
}
int wordcount(const map<string,int> &wordMap) {
// nothing to do, wordMap already contains counts
return 0;
}
// Display words and counts in wordMap, in
// alphabetical order.
void printcount(const map<string,int> &wordMap) {
map<string,int>::const_iterator i;
cout << endl;
cout << " Word : Count" << endl;
cout << "----------------- -----" << endl;
for (i = wordMap.begin();i != wordMap.end(); ++i) {
cout << setw(14) << i->first;
cout << setw(10) << i->second << endl;
}
cout << endl;
}
void removePunct(string &s) {
string::iterator i = s.begin();
while (i != s.end()) {
if ((ispunct(*i)) && (!isApostrophe(*i))) {
s.erase(i);
} else {
++i;
}
}
}
bool isApostrophe(const char c) {
return c == ''';
}
void toLower(string &s) {
string::iterator i = s.begin();
while (i != s.end()) {
*i = tolower(*i);
++i;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.