下面程序统计字符、单词和行
#include<stdio.h>
#include<ctype.h> //为isspace( )提供函数原型
#include<stdbool.h> //为bool、true和false提供定义
#define STOP '|'
int main (void)
{
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,words=%d,lines=%d,",n_chars,n_words,n_lines);
printf("pratial lines=%d\n",p_lines);
return 0;
}
检测非空白字符最简单明了的判断表达式是这样的:
c ! = ' ' && c ! = '\n' && c ! = '\t' //当c不是空白字符时,该表达式为真
检测空白字符最简单明了的判断表达式是这样的:
c == ' ' && c == '\n' && c == '\t' //当c是空白字符时,该表达式为真
但是,使用ctype.h中的 isspace( ) 函数会更简单。如果该函数的参数是空白字符,它就返回真。因为如果c是空白字符,isspace( c)为真;如果c不是空白字符,!isspace( c)为真。为了知道一个字符是不是在单词里,可以在读入一个单词的首字符是把一个标志(命名为 inword)设置为1。
这种方法在每个单词开始时将inword 设为1(真),而在每个单词结束时将其设为0(假)。仅在该标志从0变为1时对单词计数。