我正在尝试编写一个可以过滤行的 C 程序。当有连续的重复行时,应该只打印一行。我必须使用字符数组来比较这些行。数组的大小无关紧要(项目设置为 79 个字符)。我已经这样初始化了数组:
char newArray [MAXCHARS];
char oldArray [MAXCHARS];
并使用此 for 循环填充数组,以检查换行符和文件结尾:
for(i = 0; i<MAXCHARS;i++){
if((newChar = getc(ifp)) != EOF){
if(newChar != '/n'){
oldArray[i] = newChar;
oldCount++;
}
else if(newChar == '/n'){
oldArray[i] = newChar;
oldCount++;
break;
}
}
else{
endOf = true;
break;
}
}
为了循环遍历下一行并搜索重复项,我使用了一个最初设置为 true 的 while 循环。它填充下一个数组直到换行符并测试 EOF。然后,我使用两个 for 循环来测试数组。如果它们在数组中的每个位置都相同,则 duplicate 保持不变并且不打印任何内容。如果它们不相同,则将 duplicate 设置为 false 并调用一个函数 (testArrays) 来打印每个数组的内容。
while(duplicate){
newCount = 0;
/* fill second array, test for newlines and EOF*/
for(i =0; i< MAXCHARS; i++){
if((newChar = getc(ifp)) != EOF){
if(newChar != '/n'){
newArray[i] = newChar;
newCount++;
}
else if(newChar == '/n'){
newArray[i] = newChar;
newCount++;
break;
}
}
else{
endOf = true;
break;
}
}
/* test arrays against each other to spot duplicate lines*
if they are duplicates, continue the while loop getting new
arrays of characters in newArray until these tests fail*/
for(i =0; i< oldCount; i++){
if(oldArray[i] == newArray[i]){
continue;
}
else{
duplicate = false;
break;
}
}
for(i =0; i <newCount; i++){
if(oldArray[i] == newArray[i]){
continue;
}
else{
duplicate = false;
break;
}
}
if(endOf && duplicate){
testArray(oldArray);
break;
}
}
if((endOf && !duplicate) || (!endOf && !duplicate)){
testArray(oldArray);
testArray(newArray);
}
我发现这不起作用,并且无论如何都会打印连续的相同行。我不知道这是怎么发生的。我知道这有很多代码需要费力,但它非常简单,我认为另一组眼睛会很容易地发现问题。谢谢您的帮助。
最佳答案
您一次读取一个字符而不是调用 fgets() 来读取一行是否有原因?
char instr[MAXCHARS];
for( iline = 0; ( fgets( instr, 256, ifp ) ); iline++ ) {
. . .<strcmp() current line to previous line here>. . .
}
编辑: 您可能想要声明 2 个字符串和 3 个字符指针——一个指向当前行,另一个指向上一行。然后使用第三个指针交换两个指针。
关于c - 在 C 中对重复行进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50110453/