用C语言编写的程序,用于计算文本文件中某个单词的频率。
我做了这个程序,目的是统计文本文件中某个字的频率,但在计算字符。
需要帮助解决。
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE * fptr;
char ch, * word, * a;
int i=0, p=0;
word =(char *) malloc(25 * sizeof(char));
fptr = fopen("text.txt", "r");
if (!fptr)
{
printf("File not found. \n");
}
else
{
printf("Word: ");
scanf("%s", word);
while(word[p]!='\0')
{
p++;
}
a=(char *) malloc(p * sizeof(char));
while (*(ch+a) != EOF)
{
*(ch+a) = getc(fptr);
if (*(ch+a) == * word)
{
i++;
}
}
}
if (i==0)
printf("Word not found.\n");
else
{
printf("Word found %d times.\n",i);
}
fclose(fptr);
return 0;
}
你的代码中存在的错误是 getc()
只有一个字符进入内存。所以,你一定不要做这个 *(ch+a) == * word
自从 ch
有一个值,而不是一个 地址.让 ch='x'
且让 a=10
所以 *(ch+a)==*('x'+10)
这将会使你没有分配的地址被取消。
这个 网站实施 countOccurancees
函数,它取一个指向 const char
和一个文件指针,并返回字的出现次数。
词的 strstr()
通过返回一个指向所定位的子串开头的指针来帮助查找一个词的首次出现。
#define BUFFER_SIZE 100
int countOccurrences(FILE *fptr, const char *word)
{
char str[BUFFER_SIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL)
{
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
所以在 main
作用 i=countOccurrences(fptr, word);
main
应该是这样
int main()
{
FILE * fptr;
char * word;
int i=0;
word = malloc(25 * sizeof(char));//Do NOT cast
fptr = fopen("text.txt", "r");
if (!fptr)
printf("File not found. \n");
else
{
printf("Word: ");
scanf("%s", word);
i=countOccurrences(fptr, word);
}
if (i==0)
printf("Word not found.\n");
else
printf("Word found %d times.\n",i);
fclose(fptr);
return 0;
}