Hey y'all,
I need some help I am supposed to count the number of words and letter in the array and display the average amount of letters, but my program is counting the white spaces as a letter so my output is wrong. Does anyone know how to help me?
#include<iostream>
#include<cstring>
#include<string>
using namespace std;
void words(char[]);
int main ()
{
char numOfWords [2000]; // Array declaration.
cout << "Please enter a string of words you would like to count" << endl << endl; // Prompting input.
cin.getline(numOfWords, 2000); // getting input.
words(numOfWords); // Passing input to function/ calling.
int length = strlen(numOfWords);
cout << length << endl;
double avg;
avg = length/2;
cout <<" This is the average number of words in the array " << avg << endl;
return 0;
}
void words(char numOfWords[])
{
int numWords = 0; // starting count at 0.
for (int i =0; numOfWords[i] != '\0';i++) // for loop to count number of white spaces.
{
if(numOfWords[i] == ' ' )
{
numWords++;
}
}
cout << "The number of words you entered was " << numWords +1 << endl << endl; // displaying the results.
I am still having trouble with the average. If I input " bill bill" I get 2 words 8 letters and an average of 8 letters which is wrong.
/*
Author: Truly Williams.
Programming Challenge: Chapter #12 Question #2
Description: The following program display's two random number for students to add then finds the average.
*/
#include<iostream>
#include<cstring>
#include<string>
#include<iomanip>
using namespace std;
void words(char[]);
int main ()
{
char numOfWords [2000]; // Array declaration.
cout << "Please enter a string of words you would like to count" << endl << endl; // Prompting input.
cin.getline(numOfWords, 2000); // getting input.
words(numOfWords); // Passing input to function/ calling.
return 0;
}
void words(char numOfWords[])
{
double numWords = 0; // starting count at 0.
for (int i =0; numOfWords[i] != '\0';i++) // for loop to count number of white spaces.
{
if(numOfWords[i] == ' ' )
{
numWords++;
}
}
cout << "The number of words you entered was " << numWords +1 << endl << endl; // displaying the results.
double length = strlen(numOfWords); // getting the string length.
cout << " The number of letters you enter was " ;
// gtting rid of white spaces.
double letters = (length-numWords);
cout << letters << endl << endl;
double avg = (letters/numWords);
//avg = ((letters)/(numWords)); // calculating average
cout <<" This is the average number of words in the array was " << avg << endl; // Displaying avg.
If your input isn't guaranteed to be a complete sentences or might have things like double-space, etc.
You might find strtok() useful, in your case you would want to check if every token is not empty, then it's a word.