//Devin Scheu CS1A Chapter 10, P. 588, #3
//
/**************************************************************
*
* COUNT NUMBER OF WORDS IN C-STRING
* ____________________________________________________________
* This program determines the number of words in a C-string.
* ____________________________________________________________
* INPUT
* inputString : The C-string entered by the user
*
* OUTPUT
* wordCount : The number of words in the string
*
**************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
// Function to count words using pointer notation
int countWords(const char* str) {
const char* ptr = str;
int wordCount = 0;
bool inWord = false;
while (*ptr != '\0') {
if (*ptr == ' ' || *ptr == '\t' || *ptr == '\n') {
inWord = false;
} else if (!inWord) {
inWord = true;
wordCount++;
}
ptr++;
}
return (wordCount > 0) ? wordCount : 0;
}
int main () {
//Variable Declarations
const int MAX_SIZE = 100; //OUTPUT - Maximum size of the input string
char inputString[MAX_SIZE]; //INPUT - The C-string entered by the user
int wordCount; //OUTPUT - The number of words in the string
//Prompt for Input and Echo
cout << "Enter a string (max 99 characters): ";
cin.getline(inputString, MAX_SIZE);
cout << inputString << endl;
//Calculate Word Count
wordCount = countWords(inputString);
//Separator and Output Section
cout << "-------------------------------------------------------" << endl;
cout << "OUTPUT:" << endl;
//Output Result
cout << left << setw(25) << "Word Count:" << right << setw(15) << wordCount << endl;
} //end of main()