統計文本中各個字元出現的次數

來源:互聯網
上載者:User
基於huffman編碼的文本資料壓縮中的第一個階段需要統計一個文字檔中的各個字元出現的次數,以作為字元的權值進行編碼
在統計的時候我用一個結構體數組來儲存文本中出現的各個字元及其出現的次數
定義如下struct ChrCount                         
{
char chr;
int count;
} CharCount[128];
下面是我寫得程式
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *fp;
        int j=0;
int i;
struct ChrCount                //隱藏檔中的各個字元及其個數         
{
char chr;
int count;
} CharCount[128];
char c;
for( i=0;i <128;i++)
{
CharCount[i].count=0;
}
if((fp=fopen("data.txt","a+"))==NULL)
{
printf("can't open file data.txt/n");
exit(1);
}
c=fgetc(fp);
putchar(c);
CharCount[0].chr=c;
CharCount[0].count=1;
j++;
while((c=fgetc(fp))!=EOF)
{
putchar(c);
for( i=0;i <j;i++)
{
if(c==CharCount[i].chr)
{
CharCount[i].count++;
}
else
{
CharCount[j].chr=c;
CharCount[j].count++;
j++;
}
break;
}
}
fclose(fp);
printf("/n");
for( i=0;i <j;i++)
{
printf("%c: ",CharCount[i].chr);
printf("%d/n",CharCount[i].count);
}

}

這個程式的問題在於只能正確統計文本中第一個字元出現的次數,後面的字元出現一次紀錄一次,重複紀錄
請問是哪個地方出了問題?

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.