gpt4 book ai didi

c - 显示字符ASCII码及出现次数

转载 作者:行者123 更新时间:2023-11-30 20:16:04 26 4
gpt4 key购买 nike

我想编写一个程序,从文件中读取文本并显示每个字符、每个字符的 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;
}

最佳答案

首先,我不明白这有什么意义:

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

关于c - 显示字符ASCII码及出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14344625/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com