程序从文件中读取单词和文件中计算其发生 [英] Program to read words from a file and count their occurrence in the file

查看:99
本文介绍了程序从文件中读取单词和文件中计算其发生的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,我正在试图让一个程序来读取某个文件中找到每一个独特的字,并计算这个词在文件中出现的次数。我有什么目前要求用户提供一个单词,搜索文件的时候会出现这个词的数量。不过,我需要的程序本身来读取,而不是要求用户对单个字的文件。

I'm currently trying to make a program that will read a file find each unique word and count the number of times that word appears in the file. What I have currently ask the user for a word and searches the file for the number of times that word appears. However I need the program to read the file by itself instead of asking the user for an individual word.

这是我目前:

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

我只是需要一些帮助搞清楚如何读取唯一的话,虽然我的程序任何其他建议将AP preciated(它没有对尚未检查的话)的文件。

I just need some help figuring out how to read the file for unique words (words it hasn't checked for yet) although any other suggestions for my program will be appreciated.

推荐答案

如果您想打印文件中包含的每一行只有一次,你必须保存您在一个给定的数据结构中读取的字符串。例如,一个排序数组可以做的伎俩。在code可能看起来如下:

If you want to print every line contained in the file just once, you have to save the strings you have read in a given data structure. For example, a sorted array could do the trick. The code might look as follow:

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

您可以以高效的方式使用二进制搜索code函数 containString insertString 。请参见这里进一步的信息。

You may use binary search to code the functions containString and insertString in an efficient way. See here for further informations.

这篇关于程序从文件中读取单词和文件中计算其发生的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆