Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please fix my C++ code!!!!! Thank you in advance! 15. Average Number of Words If

ID: 3913442 • Letter: P

Question

Please fix my C++ code!!!!! Thank you in advance!

15. Average Number of Words If you have downloaded this book's source code from the companion Web site, you will find a file named text.txt in the Chapter 12 folder. (The companion Web site is at www.pearsonhighered.com/gaddis.) The text that is in the file is stored as on sen- tence per line. Write a program that reads the file's contents and calculates the average of words per sentence. SAMPLE RUN #2: ./avgordsPersentence Interactive Session7 Highlight: None Show Highlighted Only U countWords 23.countSentences-.5 Average number.of.words per.sentence.is.-.5

Explanation / Answer

//I have highlighted the changes in the below code in BOLD.

//Explanation: Since a sentense should contain minimum 1 word, we should increment the sentence variable (sentence++) only when we have a word count. But in your code you are taking the line count but not the sentence count. So I added the below condition.

//if(avgNumberOfWords(flag)!=0)

//{

//sentence++;

//}

//C++ Code

#include<iostream>

#include<iomanip>

#include<fstream>

#include<string>

#include<sstream>

using namespace std;

int avgNumberOfWords(const string sentense)

{

istringstream input(sentense);

string temp;

int noOfWords=0;

while(input >> temp)

{

noOfWords++;

}

return noOfWords;

}

int main()

{

string inputfile="text.txt";

ifstream input(inputfile.c_str());

string flag;

int sentence=0;

int words=0;

while(getline(input,flag))

{

words +=avgNumberOfWords(flag);

if(avgNumberOfWords(flag)!=0)

{

sentence++;

}

}

double average_words=static_cast<double>(words/sentence);

cout<<"countWords= "<<words<<" countSentences= "<<sentence;

cout<<" AVerage number of words per sentence is = "<<average_words;

}