This is an Introductory C++ course and I would like to write this program withou
ID: 3841540 • Letter: T
Question
This is an Introductory C++ course and I would like to write this program without using please. Write a C++ program that 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). It also calls a function wordcount() to count the number of times each word appears in the text. Then it calls a function 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
Explanation / Answer
#include<iostream.h>
#include<string>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;
struct item {
string data;
int count;
};
void diffwords(stringstream stream){
int count;
vector<string> list;
string word;
count = 0;
while (getline(stream, word, ' ')) { //Accessing each word
if (std::find(list.begin(),list.end(), word) != list.end())
continue;
count++;
list.push_back(word);
}
cout << count << "(";
for (int i = 0; i<list.size(); i++){
if (i < list.size -1)
cout << """ << list.at(i) << """, ", ";
else
cout << """ << list.at(i) << """, ")");
}
}
void wordcount(stringstream stream){
int count;
vector<string> list
vector<item> list1;
item temp;
string word;
while (getline(stream, word, ' ')) {
if (std::find(list.begin(),list.end(), word) != list.end()){
for (int i =0; i<list1.size(); i++){
if (list1.at(i).data == word)
list1.at(i).count++;
}
continue; // if the word is present we don't need to enter in the list
}
list.push_back(word);
temp.data = word;
temp.count = 1;
list1.push_back(temp);
}
for (int i = 0; i<list1.size()-1; i++){ // Sorting the words
for (int j = 0; j < list1.size()-i-1; j++){
if (list1.at(j).data > list1.at(j+1).data){
temp = list1.at(j);
list1.at(j) = list1.at(j+1);
list1.at(j+1) = temp;
}
}
}
for (int i = 0; i<list1.size(); i++){
cout << list1.at(i).data << " " << list.at(i).count << " ";
}
}
int main(){
string data;
cout << "Enter some text" << endl;
getline(cin, data);
stringstream stream(data);
diffwords(stream);
wordcount(stream);
}
// Output format of printcount function is not specified also its description looks very much similar to wordcount
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.