5.6(重要的词频统计发生的错误)

while(1)
    {
        c=fgetc(in);
        if(c==EOF)
            break;
        if((c>='a'&&c<='z')||(c>='A'&&c<='Z'))
        {
            flag=1;
            c=tolower(c);
            t[i++]=c;
        }
        else
        {
            if(flag)
            {
                t[i]='\0';
                T=INSERT(T,t);
                i=0;
                memset(t,0,50);
                flag=0;
            }
        }
    }

flag的存在非常重要
否则t[i]=’\0’会使得多一个空字符串
详情类似

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
typedef struct Node
{
    char word[100];
    int count;
}Node;
 Node list[1024];

int cmp(const void *p1,const void *p2)
{
    const Node *pt1=p1,*pt2=p2;
    return strcmp(pt1->word,pt2->word);
}
int main()
{
    FILE *in;
    in=fopen("article.txt","r");

    int i,j;
    for (i=0;i<1024;i++)
    {
        list[i].count=0;
    }

    char ch;
    int n=0;//单词中字母个数
    char tmp[100];
    int N=0;//实际单词数

    while(1)
    {

        ch=fgetc(in);
        if(ch==EOF)break;

        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
        {
            ch=tolower(ch);
            tmp[n]=ch;
            n++;
        }

        else
        {
            tmp[n]='\0';
            if(N==0)
            {
                strcpy(list[0].word,tmp);
                list[0].count++;
                N++;
            }

            else
            {
                int flag=0;
                for(j=0;j<N;j++)
                {
                    if(strcmp(list[j].word,tmp)==0)
                    {
                        flag=1;
                        list[j].count++;
                    }
                }
                    if(flag==0)
                    {
                        strcpy(list[N].word,tmp);
                        list[N].count++;
                        N++;
                    }
            }

            memset(tmp,0,sizeof(char)*100);
            n=0;
        }


    }


    fclose(in);
    qsort(list,N,sizeof(Node),cmp);
    for(i=1;i<N;i++)
    {
        printf("%s %d\n",list[i].word,list[i].count);
    }

    return 0 ;
}

这段代码里没有用flag判断导致最后需要强行使i从1跑到n输出

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值