There are a few thing wrong with your code :
- you're incrementing 'i' twice in your word_count function. That's not good. You're missing characters because of this and you'll probably run out of array-bounds.
Not really. There loop only increments i
. That's the only real problem.
- Why use isspace() when you can just say:
if (str[i] == ' ')
Because isspace()
will work with not only a SPACE but TAB, and the ending \0. As well as other characters. It's a much better way to go.
- and very important:
while (str[i] !='\0') i++; { if( isspace(str[i]) && !isspace(str[i+1]))
What happens when i is at the last character and the code in red is executed?
Nothing. The loop ends when the end is reached. Compares the last character with \0, which is part of the string.
Also it will still tell you one less than the actual number of words in the sentence. Because you are counting the spaces not the words. eg
Nope. Not with isspace()
.
>This looks like a C-code more than C++ and should have been posted there.
Really? i just started taking up computer this sem so i cant tell the difference. I posted it here because the program that our teach lets us use is Borland C++ 4.5
If you are taking a C++ course, the code is C++. It's just primitive. No one can expect you to know the difference if your instructor hasn't explained the difference.