c - 在C中对重复行进行排序
问题描述
我正在尝试编写一个可以通过行过滤的 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 设置为 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# - 当 ASP.NET Core API 操作上的 Date 属性无效时,模型变为 NULL
- amazon-web-services - Can't delete a Non-empty S3 bucket and Log group on deletion of CFN stack
- c++ - 当线路已经平衡时,为什么 asm 期望 ()
- c# - 如何在 ServiceStack ProxyFeature 中正确解码响应流?
- android - `ACTION_WEB_SEARCH` 在 Google 应用中启动搜索操作
- python - 基类 __init__ 中的不同行为取决于派生类
- azure-web-app-service - 如何禁用自定义事件的数据采样,但保留它用于请求?
- angular - Angular 测试 HTTP Post 调用
- android - Flutter:未定义命名参数“decoration”
- javascript - 如何将外部数据获取api导入react componentDidMount方法