gpt4 book ai didi

逐个字符比较两个文件 - C 中的文件结尾错误

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

我有一个具体问题。我必须从两个文件中读取字符串,并逐个字符地比较它们,并判断哪一行有差异以及它们有多少个字符不同。我已经制作了指针和所有内容,但问题是当涉及到第一个文件的末尾时(它需要读取较短文件的长度),我无法比较最后一个字符串,因为我的 for 循环一直持续到'\n',最后一行没有\n。但另一方面,如果我将 '\0' 放入 for 循环中,它会给出错误的结果,因为它也将 '\n' 计为 char。我该如何处理这个问题?建议?我不想使用 strcmp() 因为我需要计算字符差异,并且还有一些其他条件需要满足。这是我的问题:

while(!feof(fPointer)){
zeichnen = 0;
fgets(singleLine, 150, fPointer);
fgets(singleLine2, 150, fPointer2);
length = strlen(singleLine); // save the length of each row, in order to compare them
length2 = strlen(singleLine2);
if(length <= length2){
for(i=0; singleLine[i] != '\n'; i++){
singleLine[i] = tolower(singleLine[i]);
singleLine2[i] = tolower(singleLine2[i]);
if(singleLine[i] != singleLine2[i]){
zeichnen++;
}
}
printf("Zeile: %d \t Zeichnen: %d\n", zeile, zeichnen); // row, char

最佳答案

for(i=0; i < min(length, length2); i++) {
if ( singeLine[i] == '\n' || singleLine2[i] == '\n')
break;
/* Do work */
}

另一种方法是使用逻辑与运算符来测试 for 循环条件部分中的两个或多个条件。

来自 fgets 手册页:

char *fgets(char *s, int size, FILE *stream);

fgets() returns s on success, and NULL on error or when end of file occurs while no characters have been read.

所以你应该有 while(true) 循环并检查两个 fgets 返回值是否输入结束。

关于逐个字符比较两个文件 - C 中的文件结尾错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40192148/

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