gpt4 book ai didi

c - 如何在这段代码中使用fgets?

转载 作者:行者123 更新时间:2023-11-30 15:24:55 25 4
gpt4 key购买 nike

我需要计算文本文件中的单词数。例如该文件包含

“汉斯·穆斯特曼英戈·穆斯特曼特鲁德·穆斯特弗劳特鲁德·穆斯特曼格尔达·穆斯特”

当我搜索 Trude Mustermann 时,它应该显示 5 个匹配。

我猜我的代码只运行一行,然后就停止了。

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char const *argv[])
{
int num =0;
char word[100];
char *string;

FILE *in_file = fopen("test.txt", "r"); //reading the words

if (in_file == NULL)
{
printf("Dataerror\n"); //if word not found
exit(-1);
}

else {
fscanf("%s", word);

while(!feof(in_file))//search for the word

{
fscanf(in_file,"%s", string);
if(!strstr(string , word))//if hit a word
num++;
}

printf( "%d Hit \n" ,num );
}
return 0;
}

我尝试过使用 scanf("%[^\n]",word);getchar(); 但这没有帮助。

最佳答案

这是我很久以前学习 C 的测试之一。我记得,您需要类似以下内容:

#define numWords 2
char * words[numWords] = {"Trude", "Mustermann"};
int counters[numWords] = {0, 0};

void CountWords(char * Buffer)
{
char *p1=Buffer;
char *p2;
char *p3;
int i;
int n=0;

// initialize the counters
memset(counters, 0x00, sizeof(counters));

do
{
p2=NULL;
for (i=0; i < numWords; i++)
{
p3=strstr(p1, words[i]);
if (p3) // found a word
{
// if p2 is null or p3 is before p2
if (!p2 || p3 <= p2)
{
p2=p3;
n=i;
}
}
}
if (!p2) break; // no more words
counters[n]++;
p1=p2+strlen(words[n]);
} while (TRUE);

for (i=0; i < numWords; i++)
{
printf("The word '%s' appears %5d time/s\n", words[i], counters[i]);
}
}

要测试该功能:

CountWords("Hans Mustermann Ingo Mustermann Trude Musterfrau Trude Mustermann Gerda Muster");

如果您想从文本文件进行测试,请使用以下命令:

// To read from a file, I'd suggets to read the whole file in memory, 
// and search in that buffer.
if (_sopen_s(&FD, "test.txt", O_RDONLY | O_BINARY, _SH_DENYNO, _S_IREAD))
{
return; // file not found
}
fSize=_lseek(FD, 0, FILE_END); // get file's size
_lseek(FD, 0, FILE_BEGIN); // rewind it
// Allocate memory to read the file's content
if ((Buffer = (char *)malloc(fSize+1)) == NULL)
{
_close(FD);
return; // Not enough memory
}

__try
{
i=_read(FD, Buffer, fSize);
_close(FD);
if (i != fSize) return; // error reading the file
Buffer[fSize]=NULL;
CountWords(Buffer);
}
__finally
{
free(Buffer);
}

要从文件进行测试,您需要包含以下头文件。

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <io.h>
#include <share.h>

关于c - 如何在这段代码中使用fgets?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28154295/

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