-2

ファイルからテキストを読み取り、すべての文字、それぞれの ASCI コード、および出現回数を表示するプログラムを作成したいと考えています。私はこれを書きましたが、発生を示していません。

#include <stdio.h>
#include <stdlib.h>

int main ()
{
     FILE * pFile;

     int i=0;
     int j=0;
     char text[j];
     int ascii[256];
     int occ[256];
     int occurance=0;
     int position;
     pFile = fopen ("c:/1.in","r");
     if (pFile==NULL) perror ("Error opening file");
     else
     {
         while (!feof(pFile)) { 
         j++;
         text[j]=getc (pFile);
         ascii[j]= (int) text[j];
         position=ascii[j];
         occ[position]++;
     }
 
     for (i=1;i<j;i++){
         occurance=position[i]
  
         printf ("Chracter %c  has  ascii %d and occurs  %d times \n",   text[i],ascii[i],occ[occurance]  );}
     }
     system("PAUSE");
     return 0;
 }
4

2 に答える 2

2

まず、私はこれの要点がわかりません:

int j=0;
char text[j];

ファイル内のすべての文字を配列に入れたい場合は、ファイルのサイズとmalloc()正しいサイズをポインターに読み取ります。しかし、とにかくなぜそれをするのですか?すべての文字の出現を数えようとしている場合は、可能性を追跡してください。

完全を期すために、256 文字の配列を使用できますが、実際には、標準の印刷可能な文字だけを見ている場合、約 94 文字しかないはずです。

これ:

int main ()
{
  int temp = 0, i;
  int occ[256] = {0};
  FILE * pFile = fopen("test.txt", "r");

  if (pFile == NULL) perror("Error opening file");
  else {
     while (!feof(pFile)) { 
       temp = getc(pFile);
       if((temp < 255) && (temp >= 0)) 
         occ[temp]++;
     }
  }
//reads every character in the file and stores it in the array, then:

  for(i = 0; i<sizeof(occ)/sizeof(int); i++){
      if(occ[i] > 0)
          printf(" Char %c (ASCII %#x) was seen %d times\n", i, i, occ[i]);
  }

  return 0;
}

すべての文字、ASCII コード (16 進数)、およびそれが表示された回数を出力します。

入力ファイルの例:

fdsafcesac3sea

次の出力が得られます。

Char 3 (ASCII 0x33) was seen 1 times
Char a (ASCII 0x61) was seen 3 times
Char c (ASCII 0x63) was seen 2 times
Char d (ASCII 0x64) was seen 1 times
Char e (ASCII 0x65) was seen 2 times
Char f (ASCII 0x66) was seen 2 times
Char s (ASCII 0x73) was seen 3 times
于 2013-01-15T19:11:24.860 に答える
0

以下の単純なロジックは私にとってはうまくいきます。を取得するファイル操作を追加しますbuf

int main()
{
   char buf[] = "abcaabde";
   char val[256] = {0};
   int i = 0;
   for (i = 0; i < sizeof(buf); i++)
   {
       val[buf[i]]++;
   }

   for (i = 0; i < 256; i++)
   {
       if (val[i] != 0)
       {
           printf("%c occured %d times\n", i, val[i]); 
       }
   }

   return 0;  
}

出力は

 occured 1 times
a occured 3 times
b occured 2 times
c occured 1 times
d occured 1 times
e occured 1 times
于 2013-01-15T19:02:41.763 に答える