【发布时间】:2013-03-08 16:17:11
【问题描述】:
我目前正在尝试制作一个读取文件的程序,以查找每个唯一单词并计算该单词在文件中出现的次数。我目前向用户询问一个单词并在文件中搜索该单词出现的次数。但是我需要程序自己读取文件,而不是向用户询问单个单词。
这是我目前拥有的:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char const *argv[])
{
int num =0;
char word[2000];
char *string;
FILE *in_file = fopen("words.txt", "r");
if (in_file == NULL)
{
printf("Error file missing\n");
exit(-1);
}
scanf("%s",word);
printf("%s\n", word);
while(!feof(in_file))//this loop searches the for the current word
{
fscanf(in_file,"%s",string);
if(!strcmp(string,word))//if match found increment num
num++;
}
printf("we found the word %s in the file %d times\n",word,num );
return 0;
}
我只需要一些帮助来弄清楚如何读取文件中的唯一单词(尚未检查的单词),尽管对我的程序有任何其他建议将不胜感激。
【问题讨论】:
-
你需要保存一张你见过的单词表以及你见过它们的次数。 C 没有提供这样的机制,因此您需要自己制作或使用库,但是像树或哈希表这样的东西是合适的。
-
顺便说一句,不要像那样使用
feof()- 你应该检查fscanf()的结果(或至少首先检查)。