//Charlotte Davies-Kiernan CS1A Chapter 10 P. 589 #4
//
/******************************************************************************
*
* Compute Word Average
* ____________________________________________________________________________
* This program will accept a sentence from the user and return the number of
* words and letters within it and then the average letters per word.
*
* Formula used:
* average = (letterCount * 1.0) / wordCount
* ____________________________________________________________________________
* Input
* SIZE :Word limit for the input
* cstringInput :Cstring version of input
*
* Output
* wordCount :Amount of words in the c-string
* letterCount :Amount of letters in the string
* averageLetters :Average amount of letters per word
*****************************************************************************/
#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
//Function Prototypes
int countWords(const char *cstr);
int countLetters(const char *cstr);
int main() {
//Data Dictionary
const int SIZE = 200;
char cstringInput[SIZE];
int wordCount;
int letterCount;
float averageLetters;
//Prompt User
cout << "Enter a sentence: " << endl;
cin.getline(cstringInput, SIZE);
//Count Words and Letters
wordCount = countWords(cstringInput);
letterCount = countLetters(cstringInput);
//Compute Average
if(wordCount > 0)
averageLetters = ((letterCount) * 1.0) / wordCount;
else
averageLetters = 0;
//Display!
cout << fixed << setprecision(2);
cout << "Word count: " << wordCount << endl;
cout << "Total letters: " << letterCount << endl;
cout << "Average letters per word: " << averageLetters << endl;
return 0;
}
//Function Definitions
int countWords(const char *cstr) {
int count = 0;
bool inWord = false;
for(int i = 0; cstr[i] != '\0'; i++) {
if(!isspace(cstr[i])){
if(!inWord){
count++;
inWord = true;
}
} else {
inWord = false;
}
}
return count;
}
int countLetters(const char *cstr) {
int letterCount = 0;
for(int i = 0; cstr[i] != '\0'; i++){
if(isalpha(cstr[i])){
letterCount++;
}
}
return letterCount;
}