gpt4 book ai didi

c - 程序从文件中读取单词并计算它们在文件中的出现次数

转载 作者:太空宇宙 更新时间:2023-11-03 23:31:03 25 4
gpt4 key购买 nike

我目前正在尝试编写一个程序来读取文件,找到每个唯一的单词并计算该单词在文件中出现的次数。我目前向用户询问一个词并在文件中搜索该词出现的次数。但是,我需要程序自己读取文件,而不是向用户询问单个单词。

这是我目前拥有的:

#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;
}

我只需要一些帮助来弄清楚如何读取文件中的唯一单词(它还没有检查过的单词),尽管对我的程序的任何其他建议都将不胜感激。

最佳答案

如果您只想打印文件中包含的每一行一次,您必须将读取的字符串保存在给定的数据结构中。例如,排序数组可以解决问题。代码可能如下所示:

#include <stddef.h>

size_t numberOfLine = getNumberOfLine (file);
char **previousStrings = allocArray (numberOfLine, maxStringSize);
size_t i;

for (i = 0; i < numberOfLine; i++)
{
char *currentString = readNextLine (file);

if (!containString (previousStrings, currentString))
{
printString (currentString);
insertString (previousStrings, currentString);
}
}

您可以使用二进制搜索以有效的方式编写函数 containStringinsertString 的代码。参见 here了解更多信息。

关于c - 程序从文件中读取单词并计算它们在文件中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15508828/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com