经典的统计保留字算法
#include <iostream.h>
#include <fstream.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

struct KeyWord
{
char keyword[20];
int count;
};

KeyWord KeyWordTable[]=
{
{"else",0},{"for",0},{"if",0},{"include",0},{"while",0}
};

int SeqSearch(KeyWord *tab,int n,chr *word)
{
int i;
for(i=0;i<n;i++,tab++)
if(strcmp(word,tab->keyword)==0)
return i;
return -1;
}

int GetWord(ifstream fin,char w[])
{
char c;
int i=0;

while(fin.get(c) && !isalpha(c))
;

if(fin.eof())
return 0;

w[i++]=c;

while(fin.get(c) && (isalpha(c))
w[i++]=c;

w[i]='\0';

return 1;
}

void main(void)
{
const int MAXWORD=50;
const int NKEYWORDS=sizeof(KeyWordTable)/sizeof(KeyWord);
int n;
char word[MAXWORD],c;
ifstream fin;

fin.open("abc.cpp",ios::in|ios::nocreate);
if(!fin)
{
cerr<<"Could not open file 'abc.cpp'"<<endl;
exit(1);
}

while(GetWord(fin,word))
if((n=SeqSearch(KeyWordTable,NKEYWORDS,word)) != -1)
KeyWordTable[n].count++;

for(n=0;n<NKEYWORDS;n++)
if(KeyWordTable[n].count>0)
{
count<<KeyWordTable[n].count;
count<<" "<<KeyWordTable[n].keyword<<endl;
}
fin.close();
}

总结:
结构的定义包含内容和内容索引
结构的初始化及其计算所得的大小
结构内容的查找

获得已字母开头的词
需要跳过非字母的输入(!isalpgha(c))
需要判断文件是否到尾
需要保存满足条件的内容
字符串最后需要加‘\0’

打开文件
获得词汇
计数保存
输出结果
posted on 2006-05-10 00:33  咨询之路  阅读(192)  评论(0)    收藏  举报