# Counting words, letters, average word length, and letter frequency

I'm pretty sure my code is mostly correct. I think I'm having formatting errors more than anything. I keep receiving warnings about "double to float and int to float,possible loss of data. Here is what I am trying to accomplish exactly.

Write a function that accepts a pointer to a C- string as an argument and calculates the number of words contained in the string as well as the number of letters in the string. Communicate (or send) both of these values back to the main function, but DO NOT use global variables (variables defined outside of a function).

Write another function that accepts the number of letters and the number of words and sends the average number of letters per word (or average word size) back to the main function.

Demonstrate the functions in a program that asks the user to input a string. First, store the input in a large array. The program should dynamically allocate just enough memory to store the contents of that array. Copy the contents of the large array into the dynamically allocated memory. Then the program should pass that new, dynamically allocated array to the first function. Both the number of words and the average word size should be displayed on the screen. Round the average word size to 2 decimal places.

For instance, if the string argument is "Four score and seven years ago" the first function (word count) should calculate and send back a word count of 6 and a letter count of 25. The second function (average word size) should send back 4.17, or 25 / 6.

Extra challenge: See if you can prevent the program from counting punctuation (such as quotes or periods) as part of the sentence. Also, see if you can prevent the program from counting extra spaces as new words. For in stance, 2 spaces will often follow a colon, such as the sentence: "There are 3 primary colors : red, blue, and green." In this example, the word count should be 9 (the number 3 does count as a 1-letter word), and the letter count should be 37, for an average of 4.11

#include<iostream>
#include<string>

using namespace std;

int CountWordsAndLetters(char* str, int& words, int& letters)
{
words = 0;
unsigned int i = 0;
letters = 0;

while (str[i] == ' ')
i++;

for (; str[i]; i++)
{
if (((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z')))
letters++;
if (str[i] == ' ')
{
words++;
while (1)
if (str[i] == ' ')
i++;
else
{
i--;
break;
}

}

}
words = words + 1;
return (words);
}

float avg(float words, float letters)
{
float a = (double)(letters / words);
return a;
}

int main()
{
char array[1000000];
int words = 0;
int letters = 0;

cout << "enter the string\n\n";
gets(array);
int size;
for (size = 0; array[size]; size++);
char* str = new char[size];
strcpy(str, array);
CountWordsAndLetters(str, words, letters);

cout << "\nword count= " << words << endl;
cout << "\n letter count=" << letters << endl;
cout << "\naverage number of letters per word=" << avg(words, letters);

return 1;
}

• You should post code here once it is working. If you have specific questions about why the code is not working, you should post them on Stack Overflow. – sunny Jul 20 '15 at 21:40

It's gonna be a small review, but do you know strtok ? As said on the link I provided :

A sequence of calls to this function split str into tokens, which are sequences of contiguous characters separated by any of the characters that are part of delimiters.

So if you want to split this into words, just put the delimiters to space and punctuation, and you already have most of the job done.

An other thing :

float avg(float words, float letters)
{
float a = (double)(letters / words);
return a;
}


If you want a float, why do you explicitly cast it to a double ? That's why you have warnings.

Same goes for the typing of words and letters : can it take a negative value ? If not, why does your type allows it to do so, instead of using an unsigned type ?

And last, I think you are re-inventing strlen with this piece of code : for (size = 0; array[size]; size++);. And of course you should not, just use the function instead.

You are not fully accomplishing the task: The function

CountWordsAndLetters(str, words, letters);


Is called without assignement, so it uses global variables.

For MSDN's sake, why do you ignore all C libraries that suppose to spare you dozen of lines there?

Try using regular expressions on std:string types as follows:

First, import convenient libraries:

#include <string>
#include <regex>


Second, implement a regular expression that traps any word in a sentence which is:

std::regex rgx("(([:punct:]*)[[:alnum:]]+([:punct:]*))");


Then, put it in a function like this:

int test_regex_search(const std::string& input,int*t)
{
std::regex rgx("(([:punct:]*)[[:alnum:]]+([:punct:]*))");
std::smatch match;
if (std::regex_search(input.begin(), input.end(), match, rgx))
{
*t+=(int)(match[0].second._Ptr-input.begin()._Ptr) ;
return match[0].second-match[0].first;
}
else
return (*t=0);
}


Finally. exploit this function in main():

int main()
{
const std::string sentence = "ab cd ef";
int letters=0,words=0,ret=0,length=(int)(sentence.length());
do
{
letters+=test_regex_search(&sentence.at(ret),&ret);
words+=!!ret;
}
while(ret&(ret<length));
std::cout << " letters= " << letters  << " words= " <<  words;
}


You can give it a try here.