Skip to content

Instantly share code, notes, and snippets.

@gulan
Created November 17, 2016 17:39
Show Gist options
  • Select an option

  • Save gulan/e42a167831f0aa87387d8ab0e32eb1d4 to your computer and use it in GitHub Desktop.

Select an option

Save gulan/e42a167831f0aa87387d8ab0e32eb1d4 to your computer and use it in GitHub Desktop.
/* Count words, lines and characters.*/
/*
The number of lines is just the number of newline chars. Every
character, including newline is counter as a character. EOF is not a
character.
I use a structure design rather than an IN/OUT state flag.
A sequence of chars not including blank, tab or newline is a
'word'. A substring of a word is not itself a word.
input = (special | word)*
special = blank | tab | newline
word = char+
*/
#include<stdio.h>
int
main(int argc, char *argv[]) {
int ch;
int nline, nword, nchar;
nline = nword = nchar = 0;
ch = getchar();
while (ch != EOF) {
nchar++;
switch (ch) {
case '\n':
nline++;
ch = getchar();
break;
case ' ': case '\t':
ch = getchar();
break;
default:
nword++;
ch = getchar();
while (ch != EOF && ch != ' ' && ch != '\t' && ch != '\n') {
nchar++;
ch = getchar();
}
break;
}
}
printf("%d %d %d\n", nline, nword, nchar);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment