Advertisement
I wrote a program counting word from a string a user inputs but i am having a hard time figuring out how to go back and count the number of characters in each word and then avreaging that out. any help anyone can provide would be appreciated.
Thanks
my program goes as follows
#include <iostream>
#include <cctype>
using namespace std;
int wordCount(char * , char);
int word;
char userString;
int main()
{
const int size = 81;
char userString[size];
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout <<endl<< "Enter a string of up to 80 characters: "<<endl<<endl;
cin.getline(userString, size);
cout << " The number of words in that string are: ";
cout << wordCount(userString,size) <<endl;
cout << " The average words in this string are: ";
cout << word<<endl;
return 0;
}
int wordCount(char *strPtr , char word)
{
int index =1;
while(*strPtr != '\0')
{
if(*strPtr == ' ' )
index++;
strPtr++;
}
return index;
Thanks
my program goes as follows
#include <iostream>
#include <cctype>
using namespace std;
int wordCount(char * , char);
int word;
char userString;
int main()
{
const int size = 81;
char userString[size];
cout << "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;
cout <<endl<< "Enter a string of up to 80 characters: "<<endl<<endl;
cin.getline(userString, size);
cout << " The number of words in that string are: ";
cout << wordCount(userString,size) <<endl;
cout << " The average words in this string are: ";
cout << word<<endl;
return 0;
}
int wordCount(char *strPtr , char word)
{
int index =1;
while(*strPtr != '\0')
{
if(*strPtr == ' ' )
index++;
strPtr++;
}
return index;
Advertisement
Advertisement
-
Re: word count
Mon, May 1, 2006 - 1:06 PMSounds like homework. :)
Just off the top of my head, (no warranties implied). You need to know when a word starts and stops. This does a basic job but doesn't catch special cases. I've allowed letters and numbers to be considered as part of a word and anything else as a delimeter. So while this counts Fred69 and 42 as words it would erroneously count 3.14 as two words unless a special case for a period following a number was added. foo@bar.com would not parse right either come to think of it. But you could end up with a really huge function to try and catch every case. If I had an anal retentive teacher I would also write an input function that did not allow chars I did not want to handle.
I based this on the look of the code you were going for but you could also parse out the ending points of words using the strstr() function with a list of delimiting characters. Anyways, I'm fairly certain this compiles and probably even works.
#include "ctype.h"
int CountIt(char *str)
{
char ch;
int words = 0;
bool wordstarted = false;
do
{
ch = *str++;
if (isalnum(ch)) // ignore punctuation, use isalpha if you don't want to allow numbers in words or numbers as words.
{
wordstarted = true;
}
else
{
if (wordstarted)
{
wordstarted = false;
++words;
}
}
} while(ch);
return words;
}