是统计单词在文章里出现的次数和行数的程序,已经可以编译,但运行结果不正确,谢谢高手们帮我看看,算法中错在哪里,谢谢了 #include "string.h" #include "stdio.h" #include "alloc.h" #include "stdlib.h" #define N 10 #define M 10
struct linelist { int linenum; struct linelist *next; };
struct keyword { struct string *string1; int num; struct linelist *head,*tail; }keyword1[N];
struct string {char string2[M]; }string3[N]={'\0'}; FILE *fp=NULL; int row=0;
void init() { int i; for (i=0;i<N;i++) {keyword1[i].num=0; keyword1[i].string1=NULL; keyword1[i].head=NULL; keyword1[i].tail=NULL; } }
void fileopen() { char filename[30]; for (;;) { printf("Please input the file name:"); scanf("%s",filename); if ((fp=fopen(filename,"r"))==NULL) printf("File not found!Please input again:\n"); else break; } }
void inputkeyword() { int i; for (i=0;i<N;i++) {printf("Please input the words to search:"); scanf("%s",string3[i].string2); } }
void compare(Array) char Array[]; { int i; struct linelist *p,*q; for (i=0;i<N;i++) { if(!strcmp(Array,string3[i].string2)) { keyword1[i].num++; if (keyword1[i].num==1) { p=(struct linelist *)malloc(sizeof(struct linelist)); p->linenum=row; p->next=NULL; keyword1[i].head=p; keyword1[i].tail=p; } else if (row!=keyword1[i].tail->linenum) { q=(struct linelist *)malloc(sizeof(struct linelist)); q->linenum=row; q->next=NULL; keyword1[i].tail->next=q; keyword1[i].tail=q; } } } }
void loadcmp(Array) char Array[]; { int i,j; char *p,*q,temp[20]; q=Array; while (q!='\0') { p=q; while (q!='\0') { if (*q==' ') { p++; q++; } if (*q!=' ') {q++; if (*q==' ')break; } } j=q-p; for (i=0;i<j;i++) { temp[i]=*p; p++; } temp[j]='\0'; compare(temp); } }
void readline() { char buffer[41]; while (!feof(fp)) {row++; fgets(buffer,40,fp); loadcmp(buffer); } }
void showresult() { int i; struct linelist *p; printf("\n\n\n"); for (i=0; i<N; i++) { printf("The word "); printf("%s",string3[i].string2); printf(" "); printf("appeared in the file %d times.\n",keyword1[i].num); printf(" "); printf("They are in Line:"); p=keyword1[i].head; while (p!=NULL) { printf("%3d",p->linenum); p=p->next; } printf("\n");
} } void destroy()
{ int i; struct linelist *p,*q; for (i=0; i<N; i++) { p=keyword1[i].head; while (p!=NULL) { q=p; p=p->next; free(q); } } fclose(fp); }
main() { init(); fileopen(); inputkeyword(); readline(); showresult(); destroy(); }