下面是我的C++代码段,编译都没错,运行时输入一个和.cpp文件放一起的文件的文件名,例如“test.txt”,但在运行后,最后会输出一个已经出现记录过的字符,并且它的频率貌似溢出, 导致程序出错,可是代码没错呀,这是为什么??跪求大神指教
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
/** 保存字符个数 **/
int count = 0;
/** 保存文件名 **/
char fname[80];
char ch;//用于输出字符变量
/** 文件指针 **/
FILE *fp;
cout<<"请输入文件的名称(含后缀):";
cin>>fname;
if((fp = fopen(fname,"r")) == NULL)
{
cout<<"文件打开失败!"<<endl;
exit(1);
}
char *Array=new char[count];//创建存储字符的数组
int *countArray=new int[count];//创建用于记录字符频率的数组
int i=0;
while((ch=fgetc(fp))!=EOF)
{
count++;
Array[i]=ch;
countArray[i]=-1;//数组的内容全部置为-1,有字符则该数组变化
i++;
}
for(int j=0;j<count;j++)//开始遍历数组并记录频率
{
int sum=1;
for(int k=j+1;k<count;k++)
{
if(Array[j]==Array[k])
{
countArray[k]=0;
sum++;
}
}
if(countArray[j]!=0)
{
countArray[j]=sum;
}
}
for(int t=0;t<count;t++)//输出出现的字符并输出频率
{
if(countArray[t]!=0)
{
cout<<"元素为:"<<"“"<<Array[t]<<"”"<<" "<<"对应的频率为:"<<countArray[t]<<endl;
}
}
fclose(fp);//关闭文件
cout<<fname<<"文件里共有"<<count<<"个字符!"<<endl;
return 0;
}