How to count number of input characters, blanks and words in C

1 Answer

0 votes
#include <stdio.h> 

int main(void)
{   
    char ch;
    int nc=0,nb=0,nw=1;

    printf("Enter a string (Enter + Ctrl-C to exit): ");
    while ((ch=getchar())!=EOF)
    {
        nc++;
        
        if (ch==' ')
        {
            nb++;
            while((ch=getchar())==' ')
                nb++;
            if (ch!=' ')
                nw++;
        }
    }
    printf("total characters: %d\n",--nc);
    printf("total blanks: %d\n",nb);
    printf("total words: %d\n",nw);
    
    return 0;
}

 
/*
run:
   
Enter a string (Enter + Ctrl-C to exit): c c++ java php
total characters: 11
total blanks: 3
total words: 4

*/

 



answered Nov 3, 2016 by avibootz
...