In: Computer Science
#include <stdio.h>
#include <ctype.h>
int main(void) {
int ch;
unsigned long int charcount=0, wordcount=0, linecount=0;
while((ch=getchar())!=EOF){
if(ch==' ' || ch=='\n' || ch=='\t' || ch=='\0' || ch=='\r') {
wordcount++;
}
if(ch=='\n' || ch=='\0') {
linecount++;
}
charcount++;
}
printf("%lu %lu %lu\n", charcount, wordcount, linecount);
getchar();
return 0;
}
When my code reads a blank line, it increment my wordcount by one.
How can I fix this problem? Could you help me with this problem?
Screenshot of the code used:

The Output obtained:

The Code Used:
#include <stdio.h>
#include <ctype.h>
int main(void) {
   int ch,prev; //I have introduced another variable this
will store the character just before the current character.
   unsigned long int charcount=0, wordcount=0,
linecount=0;
   while((ch=getchar())!=EOF){
       //Actually there was a bug on line
10, to fix that we have to introduce some extra checking, in this
case
       //I have introduced another check
inside the if condition for counting the words.
       //So, what it's basically doing is,
it will check if the previous character, just before the current
character
       //is not an ' ','\n','\t','\0' or
'\r' this will make sure that the line is not blanck, and if this
condition
       //is violated than the wordcounter
would not be incremented.
       if(ch==' ' || ch=='\n' || ch=='\t'
|| ch=='\0' || ch=='\r') {
      
           if(prev!=' '
&& prev!='\n' && prev!='\t' && prev!='\0'
&& prev!='\r'){
          
    wordcount++;
           }
       }
       if(ch=='\n' || ch=='\0') {
       linecount++;
       }
       charcount++;
       prev =ch; //storing the current
character as previous, for the next iteration.
   }
   printf("%lu %lu %lu\n", charcount, wordcount,
linecount);
   getchar();
   return 0;
}
I hope you like the solution. In case of any doubts regarding the solution feel free to ask it in the comment section. If you like the solution please give a thumbs up.