How to count lines, words, and characters from input in C

1 Answer

0 votes
#include <stdio.h>

// Your program will not execute the loop until \n (Enter) is pressed

int main(int argc, char **argv) 
{ 
    int ch, lines, words, ch_count, in_word;
    in_word = lines = words = ch_count = 0;
    
    // Ctrl+C to end the program after \n (Enter) is pressed on last line
    while ( (ch = getchar()) != EOF) 
    {
        ch_count++;
        if (ch == '\n' )
            ++lines;
        if (ch == ' ' || ch == '\n' || ch == '\t')
            in_word = 0;
        else if (in_word == 0) 
             {
                in_word = 1;
                words++;
             }
    }
    printf("\nchars = %d words = %d lines = %d", ch_count, words, lines);
    
    return 0;
}

/*
  
run:
   
aa bb
cc

chars = 9 words = 3 lines = 2 // chars include space(32) and \n(10)

*/

 



answered Oct 8, 2015 by avibootz

Related questions

1 answer 179 views
1 answer 172 views
1 answer 140 views
140 views asked Oct 7, 2015 by avibootz
1 answer 240 views
1 answer 167 views
2 answers 230 views
...