/**************************************************************
*
* COUNT THE NUMBER OF WORDS AND FIND AVERAGE NUMBER OF LETTERS
* ____________________________________________________________
* This program counts the number of words in a string.The
* program asks the user to enter a string and then passes
* it to the function.The function accepts a pointer to
* a C-string as an argument and returns the number of words
* in that string. Then, the program uses a second function to
* calculate the average number of letters.
* ____________________________________________________________
* INPUT
* inWords : The string entered by the user
*
* OUTPUT
* words : Number of words in the string
**************************************************************/
#include <iostream>
#include <cstring>
#include <string>
#include <iomanip>
using namespace std;
//Prototype for functions
int CountWords(char* string);
int CountLetters(char* string);
int main()
{
//Declare variables
int SIZE = 50; // Holds size of the array
char inWords[SIZE]; // Input - String of characters entered by user
int words; // Output - Number of words in string
double average; // Output - Average number of letters
int Letters; // Holds number of letters
//Prompt user for input
cout << "Enter a string of characters." << endl;
cin.getline(inWords, SIZE);
//Call on functions CountWords and CalcAverage
words = CountWords(inWords);
words += 1;
Letters = CountLetters(inWords);
//Calculate average
average = Letters / words;
//Display number of words and average
cout << "The number of words in this string is: " << words << endl;
cout << fixed << setprecision(2);
cout << "The average number of letters is: " << average;
return 0;
}
//Define function CountWords
int CountWords(char *string)
{
int count = 0; // Counter for loop
int length; // Holds the number of words in the string
while(string[count] != '\0')
{
if(string[count] == ' ')
{
length++;
}
count++;
}
return length;
}
// Define function CalcAverage
int CountLetters(char *string2)
{
int letters = 0;
int count = 0;
while(string2[count] != '\0')
{
if(string2[count] != ' ')
{
letters++;
}
else if(string2[count] == ' ')
{
letters--;
}
count++;
}
return letters;
}