通过getchar ()来获取字符的输入,来统计字符的个数,单词的个数和行数。
通过判断在单词内和单词外来获得单词的个数,这种判断方法值得学习。。。
#include
#define IN 1
#define OUT 0
int main(void)
{
int c,stat;
int nc,nl,nw;
nc = nl = nw = 0;
stat = OUT;
while((c = getchar()) != EOF){
nc ++;
if(c == '\n'){
nl ++;
}
if(c == ' ' || c == '\t' || c == '\n'){
stat = OUT
}else if(stat == OUT){ //通过设置标志位,忽略一个单词内的字符
stat = IN;
nw ++;
}
}
printf("char %d line %d word %d \n",nc,nl,nw);
return 0;
}
首先一个问题,EOF文件结束符,一般如果直接通过终端输入进行getchar()的话只捕捉不到EOF的,可以通过文件输入
先建立一个文件,讲内容输入到一个名叫file的文件中,
然后通过 cat file | ./a.out ,这样程序就能捕捉到EOF文件结束符了。
阅读(1006) | 评论(0) | 转发(0) |