我试图创建一个程序来读取包含许多单词的文件,删除特殊字母,计算单词数,并计算它在输入文件中有多少个字符及其出现频率。
它还会根据单词长度对单词列表进行排序,单词列表及其长度和频率应在排序后写入另一个名为 Results.txt 的文件中。
当我运行它时,它变得疯狂,我无法找到错误。代码有什么问题?
#include <stdio.h>
#include <string.h>
int main ()
{
int wordcounter=1, i, j, count;
int freq[100] = {0};
int length[100] = {0};
char cc[2] = "\0"; /* gives {\0, \0} */
char word[100][100];
char temp[100];
// open the file
FILE *in = fopen("text.txt","r");
// Return if could not open file
if (in == NULL)
return 1;
while(!feof(in))
{
char c = fgetc(in);
cc[0]=c;
printf("%s", cc);
if( c=='a'||c=='b'||c=='c'||c=='d'||c=='e'||c=='f'||c=='g'||c=='h'||
c=='i'||c=='j'||c=='k'||c=='l'||c=='m'||c=='n'||c=='o'||c=='p'||
c=='q'||c=='r'||c=='s'||c=='t'||c=='u'||c=='v'||c=='w'||c=='x'||
c=='y'||c=='z'||c=='A'||c=='B'||c=='C'||c=='D'||c=='E'||c=='F'||
c=='G'||c=='H'||c=='I'||c=='J'||c=='K'||c=='L'||c=='M'||c=='N'||
c=='O'||c=='P'||c=='Q'||c=='R'||c=='S'||c=='T'||c=='U'||c=='V'||
c=='W'||c=='X'||c=='Y'||c=='Z'||c=='1'||c=='2'||c=='3'||c=='4'||
c=='5'||c=='6'||c=='7'||c=='8'||c=='9'||c=='0')
{
strcat(word[wordcounter], cc);
strcpy(word[wordcounter], strlwr(word[wordcounter]));
}
else if( c==' ' )
{
freq[wordcounter] = -1;
wordcounter++;
freq[wordcounter] = -1;
}
}
fclose(in);
for (i = 0; i < wordcounter; ++i)
{
for (j = i + 1; j < wordcounter; ++j)
{
if (strlen(word[i]) < strlen(word[j]))
{
strcpy(temp, word[i]);
strcpy(word[i], word[j]);
strcpy(word[j], temp);
}
}
}
for(i=0; i<wordcounter; i++)
{
count = 1;
for(j=i+1; j<wordcounter; j++)
{
/* If duplicate element is found */
if(strcmp(word[i], word[j])==0)
{
count++;
/* Make sure not to count frequency of same element again */
freq[j] = 0;
}
}
/* If frequency of current element is not counted */
if(freq[i] != 0)
{
freq[i] = count;
}
}
for(i=0; i<=wordcounter; i++ )
{
length[i]=strlen(word[i]);
}
for(i=0; i<=wordcounter; i++ )
{
printf("\n%s ",word[i]);
printf("%d ",length[i]); //strlen(str)
printf("%d",freq[i]);
}
FILE *out = fopen("Results.txt","w");
// Return if could not open file
if (out == NULL)
return 1;
fprintf(out, "Number of words is %d\n", wordcounter);
fprintf(out, "Word \t Length \t Freq \n");
for(i=0; i<=wordcounter; i++ )
{
fprintf(out, "%s \t %d \t %d \n", word[i], length[i], freq[i]);
}
fclose(out);
return(0);
}