You're incrementing c
twice for the space character.
Your if
statement should be just:
if(ch==32)
++w;
You have another subtle bug as well inasmuch as the string hellospcspcthere (with two spaces) will register as three words in your code.
This is how I would have written it to avoid those problems. Note the use of lastch
to avoid counting space sequences as multiple words.
int main(void) {
int ch = ' ', lastch, w = 0, c = 0;
do {
lastch = ch;
ch = getchar();
++c;
if (ch == ' ') {
if (lastch != ' ') {
++w;
}
}
} while (ch != '\n');
if (lastch != ' ') {
++w;
}
printf("num of characters is %d\n",c);
printf("num of words is %d\n",w);
return 0;
}