首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

从资料中读单词并统计个数

2013-10-07 
从文件中读单词并统计个数#includestdio.h#includestdlib.h#includestring.htypedef struct wstr{ch

从文件中读单词并统计个数
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct wstr
{
char w[50];
int count;
struct wstr *next;
}WORD;
void main()
{
    FILE *fp;
WORD *h,*p,*q;
char word[50];
h=(WORD*)malloc(sizeof(WORD));
h->next=NULL;
    p=h->next;
if((fp=fopen("s.txt","r"))==NULL)
{
printf("Can't open file");
    return;
}
while(fscanf(fp,"%s",word)!=EOF)

    q=h->next;
while(q!=NULL&&strcmp(q->w,word))
   q=q->next;
 if(q!=NULL)
q->count++;
 else{
 q=(WORD*)malloc(sizeof(WORD));
 strcpy(q->w,word);
 q->count=1;
 q->next=NULL;
 }
}
 while(p!=NULL)
 {
 printf("%s  %d",p->w,p->count);
 p=p->next;
 }
}
我 写了个程序,统计s.txt文件中单词以及其出现频率,可是编译没错,运行不出来,求解

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct wstr
{
char w[50];
int count;
struct wstr *next;
}WORD;

void main()
{
    FILE *fp;
WORD *h,*p,*q;
char word[50];
h=(WORD*)malloc(sizeof(WORD));

h->next=NULL;
p=h;//h->next

if((fp=fopen("s.txt","r"))==NULL)
{
printf("Can't open file");
    return;
}


while(fscanf(fp,"%s",word)!=EOF)

    q=h->next;
while(q!=NULL&&strcmp(q->w,word))
q=q->next;

if(q!=NULL)
q->count++;
else
{
q=(WORD*)malloc(sizeof(WORD));
strcpy(q->w,word);
q->count=1;
q->next=NULL;
//新加的
p->next=q;
p=p->next;

}
}
//新加的
p=h->next;
 while(p!=NULL)
 {
 printf("%s  %d",p->w,p->count);
 p=p->next;
 }
}

[解决办法]

void insert(struct wstr *head, struct wstr *i_new)
{
int n = 0;
struct wstr *p, *q;

p = head;
q = head->next;
while(q)
{
while(q->w[n] == i_new->w[n])//跳过前面相等的字符,你也可以使用字符比较函数
{
++n;
}
if (q->w[n] > i_new->w[n])//q字符大于i_new字符,插在i_new之前,返回
{
p->next = i_new;
i_new->next = q;
return;
}
else//q字符小于i_new字符,下偏移一个结点,继续
{
n = 0;
p = q;
q = q->next;
}

}//循环结束,说明只能插入到尾部
i_new->next = q;
p->next = i_new;

}
void main()
{
...
while(fscanf(fp,"%s",word)!=EOF)
 {  
while(q!=NULL&&strcmp(q->w,word))
    q=q->next;
  if(q!=NULL)
 q->count++;
  else{
  q=(WORD*)malloc(sizeof(WORD));
  strcpy(q->w,word);
  q->count=1;
  insert(h, q);
  }
 
...
}


临时写的,你自己测试一下

热点排行
Bad Request.