// Andres Guzman CSC5 Chapter 10, P. 588, #3
/******************************************************************************
*
* DISPLAY ESSAY WORD COUNT
* ____________________________________________________________________________
* Program function will accept pointer to a c-string as an argument and will
* return the number of words typed.
*
* Computation:
*
* Function will compute using if statements nested inside a for loop
* ____________________________________________________________________________
*
* INPUT
*
* SIZE = Array size of characters
* sentence = Holds entered characters
*
* OUTPUT
*
* wordcount = total words counted
*
******************************************************************************/
#include <iostream>
#include <cctype>
using namespace std;
int words(char *a); //Function Prototype
int main()
{
const int SIZE = 1000; //Array Size
char sentence[SIZE]; //Array
cout << "Enter a Sentence: ";
cin.getline(sentence, SIZE); //Allows entire entered line with SIZE limit
//
//Function call inside console output
cout << "\nThere are " << words(sentence)
<< " Words in this Sentence." << endl;
}
/*******************************************************************************
* Adding Definition to function. This function will step through each character
* of the array and determine whether it is a whitespace character or is a null
* terminator. If it isn't a whitespace character, it will check whether it is
* the beginning of the subscript, or if the prior element of the subscript was
* a whitespace character.
******************************************************************************/
int words(char *a)
{
int wordcount = 0; //Accumulator
//
//Initializing for loop to step through subscript array
for (int count = 0; a[count] != '\0'; count++)
{
if(!isspace(a[count]) && (count == 0 || isspace(a[count - 1])))
wordcount++; //Increments if both conditions are true
}
return wordcount; //Returns word count
}