//wordcnt.c --Count the number of words, words, and lines
#include<stdio.h>
#include<ctype.h>//Provide a prototype for the isspace() function
#include<stdbool.h>//For bool, Provide definitions for true, false
#define STOP'|'
int main(void)
{ char c;//Read the character char prev;//The previous character read long n_chars = 0L;//Number of characters int n_lines = 0; //Number of lines int n_words = 0;//Number of words int p_lines = 0;//Number of incomplete lines bool inword = false;//If c is in a word, inword is equal to true
printf("Enter text to be analyzed (| to terminate):\n");
prev = '\n'; //用于识别完整的行
while ((c = getchar())!=STOP)
{
n_chars++; //统计字符
if (c == '\n')
n_lines++;
if (!isspace(c) && !inword)
{
inword = true;//开始一个新的单词
n_words++;//统计单词
}
if (isspace(c) && inword)
inword = false; //打到单词的末尾
prev = c; //保存单词的值
}
if (prev != '\n')
p_lines = 1;
printf("characters = %ld,words = %d,lines = %d,", n_chars, n_words, n_lines);
printf("partial lines = %d\n", p_lines);
return 0;
}