-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 码(十六进制)和它显示的次数。

一个示例输入文件:

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

Below simple logic works fine for me. Add file operations to get the 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;  
}

Output is

 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 回答