这个是我在学习C Primer Plus中目前碰到的比较有意思的用标记变量的方法统计单词数的一道题。 代码如下。
#include<stdio.h>
#include<ctype.h> //包含了isspace()函数判断空格,若是空格返回真
#include<stdbool.h> //包含了bool true false用于标记变量
#define STOP '|' //此时还是没有用EOF来停止循环
int main()
{
char c; //输入的字符
char prev; //前一个字符,用来判断不完整行
long n_chars = 0; //字符数
int n_lines = 0; //行数
int n_words = 0; //单词数
int p_lines = 0; 不完整行数(1或0)
bool inword = false; //初始为false,若c在单词中则为真
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为真,说明是单词的第一个字符
将inword变为真(这样这个单词后面的字符就不会算进单词数中,
因为不满足此if条件了),单词数增加
{
inword = true;
n_words++;
}
if(isspace(c) && inword)
//若是空格且inword是真了,那么说明单词结束,进入空格,
则将inword变为假 开始准备加下一个单词数
inword = false;
prev = c; //将输入的字符赋成上一个字符
}
if(prev != '\n') //若最后一个字符不是换行符,说明有不完整行,为1
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;
}
此题关键在bool标记变量的运用,通过true/false来判断是否为单词。
欢迎交流探讨。
谢谢。