gpt4 book ai didi

c - fgets() 陷入无限循环

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

如果我使用 fgets() 函数在整个文本文件中搜索特定的分隔符,我该如何确保 fgets() 不会在 EOF 处无限循环?

我将从 delimiter1 到 delimiter2 的所有行连接到 struct1[i].string1,其中 i 是 delimiter1/delimiter2 模式的第 n 次出现。这种模式在整个文本文件中一直持续到最后,那里没有定界符 2,而是 EOF。我也想连接从 delimiter1 到 EOF 的所有内容。

int i;
while(fgets(temp_string,100,inFile) != NULL){
if(strcmp(temp_string,"Delimiter1")==0){ //checks to see if current line is delimiter1
j=strcmp(temp_string,"Delimiter2");
while(j!=0 && temp_string != NULL){ //Here I try to exit if it is the EOF
fgets(temp_string,100,inFile);
strcat(struct1[i].string1,temp_string);
j= strcmp(temp_string,"Delimiter2"); //update comparator
}
i++;
}

}
}

但是,当我尝试运行这段代码时,我陷入了无限循环。我在内部 while 循环中放置了一个打印语句,显示整数“i”是什么,它停留在数字 4,这是文本文件中 delimiter1 的总数,这让我相信 EOF 给了我无限循环。

如有任何帮助,我们将不胜感激。

最佳答案

无限循环的原因是内循环:

 while(j!=0 && temp_string != NULL){ //Here
^ ^ never set to NULL
| never became 0 if "Delimiter2" not found

假设,如果在 temp_string 中的值是不是 "Delimiter2" 那么你永远不会设置为 j = 0 而且你也没有设置temp_string 为 NULL

您一次读入了 temp_string 100 字符,因此 "Delimiter2" 可能会与其他一些字符一起从文件中读取,这就是 strcmp() 不返回 0 的原因即使在阅读 "Delimiter2" 时也是如此。

尝试通过 printf you temp_string 来调试您的代码。

另外,您可以使用 strstr() 函数代替 strcmp() 在您的文件中查找 "Delimiter2"strstr() 如果 "Delimiter2" 在 temp_string 中找到任何位置,则返回有效地址,否则返回 NULL。

关于c - fgets() 陷入无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15652563/

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