gpt4 book ai didi

C 初学者 : How to search for particular words in a file (line by line) in C

转载 作者:太空狗 更新时间:2023-10-29 14:57:50 25 4
gpt4 key购买 nike

我需要在文件中逐行搜索两个特定的单词,如果它们存在,则打印“Found!”。

这是 file.txt(有四列)

bill gates 62bill microsoft 
beyonce knowles 300mill entertainment
my name -$9000 student

以下是我的想法,但似乎行不通

char firstname[];
char lastname[];
char string_0[256];

file = fopen("file.txt","r+");

while((fgets(string_0,256,file)) != NULL) {

//scans the line then sets 1st and 2nd word to those variables
fscanf(file,"%s %s",&firstname, &lastname);

if(strcmp(firstname,"beyonce")==0 && strcmp(lastname,"knowles")==0){
printf("A match has been found");
}
}

fclose(file);

请帮忙。会不会是while循环中指针没有移动到下一行?如果是这样,我该如何解决?

最佳答案

在您已经使用fgets 读取文件 之后,与其调用fscanf,不如调用sscanf 在您要在 fgets 调用中将数据复制到的 string_0 变量上。

关于C 初学者 : How to search for particular words in a file (line by line) in C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10239771/

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