7.4 一个统计单词的程序
判断非空白字符最直接的测试表达式是:
c != ' ' && c != '\n' && c != '\t'
检测空白字符最直接的测试表达式是:
c == ' ' || c == '\n' || c == '\t'
使用ctype.h头文件中的函数isspace()更简单。如果该函数的参数是空白字符,则返回真。所以,如果c是空白字符,isspace(c)是真;
如果c不是空白字符,!isspace(c)为真。
如果使用布尔类型的变量,通常习惯把变量本身作为测试条件。如下所示:
这里inword的值不是1就是0。
用if( inword )代替if( inword == true )
用if( !inword )代替if( inword == false )
可以这样做的原因是,如果inword为true,则表达式inword == true为true;如果inword为false,则表达式inword == true为false。
所以,还不如直接用inword作为测试条件。类似地,!inword的值与表达式inword == false的值相同(非真即false,非假即true)。
// wordcnt.c -- counts characters, words, lines
#include <stdio.h>
#include <ctype.h> // for isspace()
#include <stdbool.h> // for bool, true, false
#define STOP '|'
int main(void)
{
char c; // read in character
char prev; // 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 partial lines
bool inword = false; // == true if c is in a word
printf("Enter text to be analyzed (| to terminate):\n");
prev = '\n'; // used to identify complete lines
while ((c = getchar()) != STOP)
{
n_chars++; // count characters
if (c == '\n')
n_lines++; // count lines
if (!isspace(c) && !inword)
{
inword = true; // starting a new word
n_words++; // count word
}
if (isspace(c) && inword)
inword = false; // reached end of word
prev = c; // save character value
}
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;
}
/* 输出:
*/
如果c不是空白字符,且inword为假
翻译成如下C代码:
if( !isspace( c ) && !inword )
上面的整个测试条件比单独判断每个空白字符的可读性高:
if( c != ' ' && c != '\n' && c != '\t' && !inword )
把ch的char类型改为int类型,while循环的中表达式STOP改为EOF就可以统计文件中的单词数量了。