Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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

...