编写程序,统计行数、单词数和字符数。这里的单词指其中不包含空格、制表符或者换行符的字符序列。
/* wordcnt.c */
#include <stdio.h>
#define IN 1 /* 正在读入单词 */
#define OUT 0 /* 结束读入单词 */
int main() {
int c;
long wordcnt;
long linecnt;
long charcnt;
int inword;
wordcnt = linecnt = charcnt = 0;
inword = OUT;
while ((c = getchar()) != EOF) {
if (c == '\n') {
++linecnt;
}
if (c == ' ' || c == '\n' || c == '\t') {
if (inword) {
++wordcnt;
inword = OUT;
}
} else {
inword = IN;
}
++charcnt;
}
printf("wordcnt = %ld;\nlinecnt = %ld;\ncharcnt = %ld.\n",
wordcnt, linecnt, charcnt);
return 0;
}
程序定义了两个符号常量 IN 和 OUT 而不是直接使用对应的 1 和 0(幻数),在较大的程序中(不是指上面的小程序),符号常量替代幻数有利于提高程序的可读性,如果需要对数值进行修改,也会相对容易很多。
在兼有值和赋值两种功能的表达式中,赋值结合次序是由右至左的:
wordcnt = linecnt = charcnt = 0;
/* 等价于 */
wordcnt = (linecnt = (charcnt = 0));
编译运行结果如下:需要留意的是,行数是依据换行符 \n
来统计的,因此输入最后一行之后,必须再键入一次换行,否则统计出来的行数将会少 1 。
$ ./wordcnt.out
april is a dog's dream
the soft grass is growing
the sweet breeze is blowing
the air all full of singing feels just right
wordcnt = 24;
linecnt = 4;
charcnt = 122.
顺便说一下,Linux 下用 wc (word count)命令从标准输入流或者文件读取数据,用以统计行数、单词和字符数。
比如说当前文件目录下有一个 april.log 的文件,它里面的内容如下:
$ cat -n april.log
1 april is a dog's dream
2 the soft grass is growing
3 the sweet breeze is blowing
4 the air all full of singing feels just right
5 so no excuses now
6 we're going to the park
7 to chase and charge and chew
8 and I will make you see
9 what spring is all about
10
$
调用 wc 命令:
$ wc april.log
10 50 243 april.log
$
网友评论