我正在尝试实现计算文本文件中单词数的函数。
到目前为止,这是我的尝试。
#include <stdio.h>
#include <string.h>
int main()
{
FILE *fp;
char word[1000];
int count = 0, i;
int *ptr = NULL;
printf("Enter filename: ");
scanf("%s", word);
fp = fopen(word, "r");
while(fscanf(fp, "%s", word) != EOF) //dynamically allocate contents of the file into word
ptr = (int *)malloc(sizeof(int));
for(i = 0; i < 4000; i++)
{
if(word[i] == ' ')
count++;
}
printf("Total: %d", count);
return 0;
}//main
当我使用 gcc- 编译时,我得到了类似"variable ' ptr
' set but not used" 之类的错误,但我以为我在将文件内容动态分配到word[80]
.
我认为我的单词计数器有严重问题......当明显有 200 多个单词时,它也会返回 0。有人可以启发我吗?