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

Write the function int countWords(string str) that returns a count of all words

ID: 3556340 • Letter: W

Question

Write the function int countWords(string str) that returns a count of all words in the string str. Words

are separated by one or more spaces. Strings should be requested from the user via a loop construct for

acquiring test data.

Example run (with user input indicated with bold italics):

Enter a string or Q to quit: The quick brown fox jumped over the lazy dog.

Word count: 9

Enter a string or Q to quit: aeiou AEIOU

Word count: 2

Enter a string or Q to quit: zxcvbnm

Word count: 1

Enter a string or Q to quit: Q

Explanation / Answer

#include <iostream>
#include <string>
#include <sstream>
int main()
{
     std::string thatString;
     std::cout << "Please enter a word, a sentence, or a string of numbers: ";
     getline(std::cin, thatString);
     // remember that cin >> s; reads one WORD at a time?
     int words=0;
     std::istringstream is(thatString);
     while(is >> thatString)
         ++words;
     // done!
     std::cout << "There are(is) " << words << " word(s) in the phrase you entered.";
}