Hey guys,
I need your help in figuring this out.
It sounds fairly easy and I can do this code when it comes to just counting every word encountered by 1 space after it or the null terminator.
However, my design requirements are to make a function that define a word as (one or more alphabetic characters separated by one or more spaces).
I also cannot include any number/digit values that are entered into the C-String.
It is these two requirements that have me confused.
#include <iostream>
usingnamespace std;
// Function Prototype
int wordCount (char *userEntry);
int main()
{
// Constants
constint MAX_LENGTH = 150;
// Local variables
char userWords[MAX_LENGTH+1] ;
int wCount = 0;
// Get the user input line of text.
cout << "Enter text less than or equal to " << MAX_LENGTH << " characters:\n";
cin.getline(userWords, MAX_LENGTH+1);
// Count the number of words entered.
wCount = wordCount (userWords);
// Display the number of words entered
cout << "\nNumber of words in the entered text is: " << wCount << endl;
return 0;
}
// ********************************************************
// **
// ** Function Name: wordCount
// ** This function counts the # of space-delimited words
// ** in a text string, and returns the count to the caller.
// **
// **
// ********************************************************
int wordCount (char *userEntry)
{
int totalWords = 0;
while (*userEntry != '\0')
{
if ((*userEntry == ' ' && *(userEntry + 1) != ' '))
{
totalWords += 1;
userEntry++;
}
elseif (isalpha(*userEntry))
userEntry++;
elseif (*userEntry == '\0' ||*userEntry == '.' || *userEntry == '?'
|| *userEntry == '!')
{
totalWords += 1;
userEntry++;
}
elseif (isdigit(*userEntry))
userEntry++;
}
return totalWords;
}
int wordCount(char *userEntry)
{
int count = 0;
bool inWord = false;
char *cp = userEntry;
while (*cp++)
{
if (isalpha(*cp))
{
if (!inWord) // new word
{
inWord = true;
count++;
}
}
else // any other char
{
if (inWord) // end of word found
inWord = false;
}
}
return count;
}
The character(s) should match one of my if or else if statements.
But what if you've missed something? You're not checking for all of the different "types" of characters so it is possible that the user will enter something you missed (ie: ';' and quite a few others).
By the way the program runs to completion for "Hello my name is MisterTams!" for me.
But there are some oddities:
1 2 3 4 5 6 7 8 9 10
$ homework
Enter text less than or equal to 150 characters:
Hello World
Number of words in the entered text is: 1
$ homework
Enter text less than or equal to 150 characters:
Hello World!
Number of words in the entered text is: 2