统计字符数、单词数、行数
伪代码:
读取一个字符
当有更多输入时
递增字符数
如果读完完整一行,递增行数
如果读完一个单词,递增单词计数
读取下一个字符
输入实例
reason is a
powerful servant but
an inadequate master
|
输出示例:
characters=55,words=9,lines=3,partial lines=0
程序示例:
#include<stdio.h>
#include<ctype.h> //isspace()函数原型声明;如果参数是空白字符,isspace()=1
#include<stdbool.h> //bool、true、false提供定义
#define STOP '|'
int main()
{
char c; //读入字符
char prev; //读入的前一个字符
long n_chars = 0L; //字符数
int n_lines = 0, n_words = 0;
int p_lines = 0; //不完整的行数
bool inword = false; //读入单词首字符时把标志位(inword)置1
printf("enter text to be anylzed (| to termeniante ):\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;
}