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

Objective: To input a sentence and count its words and find the longest word. Wr

ID: 3643532 • Letter: O

Question

Objective: To input a sentence and count its words and find the longest word.

Write a program that has the user type a sentence, and stores the entire sentence in one cstring or one string object. It should then output the number of words and characters in the sentence, as well as the length of the longest word.

Rules:
Your program should allow input of up to 80 characters in a sentence (or more if you wish).
You must store the entire sentence in a cstring (a null-terminated array of characters) or in a single string object, before counting characters or words.
You must include in your program a function with one of the following prototype declarations to count the number of words in the sentence:

// return the number of words in the string "sentence"
// and output the length of the longest word
int countWords(const char sentence[]);

or

int countWords(string sentence);

You may assume that the sentence fits on one line, has no punctuation, and has just one space between words.
You must demonstrate your program using the test cases shown here.

Here is some sample output from the program:

Please enter a sentence.
The fox said goodbye
Your sentence has 20 characters.
The longest word has 7 letters in it.
The sentence has 4 words.

Please enter a sentence.
This is my test of a long sentence with several words
Your sentence has 53 characters.
The longest word has 8 letters in it.
The sentence has 11 words.

Please enter a sentence.
Hi
Your sentence has 2 characters.
The longest word has 2 letters in it.
The sentence has 1 words.

Explanation / Answer

//Here ya go

// Don't forget to rate :)

//-------------------------------

#include <iostream>
#include <string>

using namespace std;

int countWords (const char []);



int main()
{
char Phrase [81];
int NumWords = 0;


cout << "Please enter a sentence." << endl;
cin.getline (Phrase, 81);


cout << "Your sentence has " << strlen(Phrase) << " characters." << endl;

NumWords = countWords (Phrase);

cout << "The sentence has " << NumWords << " words." << endl;
}

int countWords (const char str [])
{
   bool inSpaces = true;
   int numWords = 0;
   int MaxSize = 0;
   int CurSize = 1;

   for (int i = 0; str [i] != ''; i++)
   {
      if (str [i] == ' ')
      {
         inSpaces = true;
         CurSize = 0; // Reached space so that is the end of the word
      }
      else if (inSpaces) // Basically was last character a space if so then start of a new word
      {
         numWords++;
         inSpaces = false;
      }
      CurSize++; // letter in word processed
    if (MaxSize < CurSize)
        MaxSize = CurSize;
   }
   cout << "The longest word has " << (MaxSize - 1) << " letters in it." << endl;
   return numWords;
}