一个统计单词的程序

来源:互联网 发布:淘宝权限管理 编辑:程序博客网 时间:2024/06/05 06:43
#include<stdio.h>
#include<ctype.h>
#include<stdbool.h>
#define STOP '|'
int main()
{
char c;
char prev;
long n_chars = 0L;
int n_lines = 0;
int n_words = 0;
int p_lines = 0;
bool inword =false;

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,word %d, lines =%d, ",
n_chars, n_words, n_lines);
printf("partial lines  =%d\n",p_lines);
return 0;

}

这个程序高明之处在于,在读到每个单词开头时把inword设为1,在读到每个单词结尾时把inword设为0.只有在标记从0设置为1时,递增单词计数。

0 0
原创粉丝点击