Counts characters, words, lines - C Data Type

C examples for Data Type:char

Description

Counts characters, words, lines

Demo Code

#include <stdio.h>
#include <ctype.h>         // for isspace()
#include <stdbool.h>       // for bool, true, false

#define STOP '|'//from w ww.j av a 2 s  .c om

int main(void)
{
    char c;                 
    char prev;              // previous character read
    long charCount = 0L;      
    int lineCount = 0;        
    int wordCount = 0;        
    int partialLineCount = 0; 
    bool inword = false;    // == true if c is in a word
    
    printf("Enter text to be analyzed (| to terminate):\n");
    prev = '\n';            // used to identify complete lines
    while ((c = getchar()) != STOP)
    {
        charCount++;          // count characters
        if (c == '\n')
            lineCount++;      // count lines
        if (!isspace(c) && !inword)
        {
            inword = true;  // starting a new word
            wordCount++;      // count word
        }
        if (isspace(c) && inword)
            inword = false; // reached end of word
        prev = c;           // save character value
    }
    
    if (prev != '\n')
        partialLineCount = 1;
    printf("characters = %ld, words = %d, lines = %d, ",
           charCount, wordCount, lineCount);
    printf("partial lines = %d\n", partialLineCount);
    
    return 0;
}

Result


Related Tutorials