//Zachary Abdollahi CS1A Chapter 10, P. 588, #3
/*******************************************************************************
*
* COUNT WORDS IN STRING
*_______________________________________________________________________________
* This program accepts a C-string from the user, passes a
* pointer to the C-string to a function that counts the number
* of words contained in the string, and displays the word count.
*_______________________________________________________________________________
* INPUT
* userString : C-string entered by the user
*
* OUTPUT
* wordCount : Number of words contained in the C-string
*
*******************************************************************************/
#include <iostream>
#include <cctype>
using namespace std;
// Function Prototype
int countWords(const char *strPtr);
int main ()
{
const int SIZE = 200; // Maximum C-string size
char userString[SIZE]; //INPUT
int wordCount; //OUTPUT
// Input String
cout << "Enter a string: ";
cin.getline(userString, SIZE);
// Compute Word Count
wordCount = countWords(userString);
// Output Result
cout << "The string contains " << wordCount << " words." << endl;
return 0;
}
/*******************************************************************************
*
* FUNCTION countWords
*_______________________________________________________________________________
* This function accepts a pointer to a C-string, counts the
* number of words separated by whitespace characters, and
* returns the total word count as an integer.
*_______________________________________________________________________________
* INPUT
* strPtr : Pointer to a null-terminated C-string
*
* OUTPUT
* words : Integer count of words in the C-string
*
*******************************************************************************/
int countWords(const char *strPtr)
{
int words = 0; //OUTPUT
bool inWord = false; // Flag to track if currently inside a word
while (*strPtr != '\0')
{
if (isspace(*strPtr))
{
inWord = false;
}
else if (!inWord)
{
inWord = true;
words++;
}
strPtr++;
}
return words;
}