【问题标题】:How do I count occurrences of a list of strings and output them to a new file?如何计算字符串列表的出现次数并将它们输出到新文件?
【发布时间】:2014-06-03 10:30:34
【问题描述】:

我收到了三个“.txt”文件。

第一个是单词列表。 第二个是要搜索的文档。 第三个是一个空白文档,我的输出将写入其中。

我应该获取第一个文件中的每个单词,搜索第二个文件并将第三个文件中的出现次数打印为“wordX = numOccurences”。

我有一个很好的函数可以返回 wordCount,它会正确返回第一个单词,但我会得到所有剩余单词的零。

我试图取消对所有内容的引用,但我想我已经停滞不前了。 “指针谈话”有问题。

我还没有开始将单词输出到新文件,但是 printf 语句应该是附加模式下的 print to file 语句。很容易。

这是有效的 wordCount 函数 - 如果我只给它一个单词,例如“测试”,它就可以工作,但如果我给它一个我想要迭代的数组,它只会返回 0。

int countWord(char* filePath, char* word){  //Not mine. This is a working prototype function from SO, returns word count of particular word
FILE *fp;
int count = 0;
int ch, len;

if(NULL==(fp=fopen(filePath, "r")))
    return -1;
len = strlen(word);
for(;;){
    int i;
    if(EOF==(ch=fgetc(fp))) break;
    if((char)ch != *word) continue;
    for(i=1;i<len;++i){
        if(EOF==(ch = fgetc(fp))) goto end;
        if((char)ch != word[i]){
            fseek(fp, 1-i, SEEK_CUR);
            goto next;
        }
    }
    ++count;
    next: ;
}
end:
fclose(fp);
return count;
}

这是我程序的一部分,尝试在循环从第一个文件中获取所有单词时调用该函数。循环正在抓取单词,因为它会打印它们,但 wordCount 不接受第一个单词之外的任何内容。

int main(){     


FILE *ptr_file;

char words[100];

ptr_file = fopen("searchWords.txt", "r");
if(!ptr_file)
  return -1;

while( fgets(words, 100, ptr_file)!=NULL )
 { 
   int wordCount = 0;

   char key[100] = &*words;
   wordCount = countWord("document.txt", words);
   printf("%s = %d\n", words, wordCount);  

 } 


  fclose(ptr_file);

  return 0;    

}

【问题讨论】:

  • Show countWord function..problem 似乎在那里
  • 编辑显示功能

标签: c arrays string pointers io


【解决方案1】:

fgets 也读取 \n。这就是问题所在。引用

换行符使 fgets 停止读取,但它被函数视为有效字符并包含在复制到 str 的字符串中。

要解决这个问题,请更改它

while( fgets(words, 100, ptr_file)!=NULL )
{
    int len = strlen(words);
    words[len-1] = '\0';

【讨论】:

  • 吹毛求疵:if (words[len-1] == '\n')
【解决方案2】:

一个直接的问题:fgets 不会从字符串中去除行尾,所以无论你传递给countWord 都有一个嵌入的换行符。

【讨论】:

    猜你喜欢
    • 2014-09-13
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 2018-04-29
    • 2011-10-08
    • 2016-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多