It looks like you've copied this code from somewhere. Have you any idea what it does or how it works?
I'll add comments to the search function to help, but it's difficult to help if we don't know how much you know.
1 2 3 4 5 6 7 8 9 10 11 12 13
int wordsstr(constchar*pstr)
{
int count = 0; // I added this, counter starts off at zero
while (*pstr!='\0') // while we've not hit the end of the string
{
if (*pstr==' ') // check if the character is a space
{
count++;// increment the counter
}
pstr++; // move to the next character in the string
}
return count+1; // return one more than count
}
No it didn't. It counted the number of spaces. If there were the same number of words as spaces, then that's just lucky. If you pass "", it will return 1. If you pass " " (5 spaces) it will return 6.
To count words, you need to count the transitions from non-letters to letters.