You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言实现连续重复行过滤:字符数组方案技术问询

Alright, let's get your C program for filtering consecutive duplicate lines up and running. You’ve already laid the groundwork with your two character arrays and started the line-reading loop—here’s how to flesh out the rest of the logic correctly:

Full Implementation

First, let's start with the complete code, then break down the key parts:

#include <stdio.h>
#include <string.h>

#define MAXCHARS 79  // As specified in your project

int main() {
    char newArray[MAXCHARS];
    char oldArray[MAXCHARS] = "";  // Initialize to empty for first line comparison
    int i;
    int newCh;

    while (1) {
        // Read each line into newArray (your loop, completed)
        for (i = 0; i < MAXCHARS - 1; i++) {  // Leave space for null terminator
            newCh = getchar();
            
            // Stop at newline or end of file
            if (newCh == '\n' || newCh == EOF) {
                break;
            }
            newArray[i] = newCh;
        }
        // Null-terminate the array to make it a valid C string
        newArray[i] = '\0';

        // Exit loop if we hit EOF with no characters read
        if (newCh == EOF && i == 0) {
            break;
        }

        // Compare current line with the previous one
        if (strcmp(newArray, oldArray) != 0) {
            // Print the line only if it's not a duplicate
            printf("%s\n", newArray);
            // Update oldArray to the current line for next iteration
            strncpy(oldArray, newArray, MAXCHARS);
            oldArray[MAXCHARS - 1] = '\0';  // Ensure null termination even if array is full
        }
    }

    return 0;
}
Key Details to Note
  • Null Termination: This is non-negotiable in C! We add '\0' to newArray after reading characters because functions like strcmp and printf rely on null-terminated strings to work correctly.
  • Buffer Overflow Prevention: We use MAXCHARS - 1 in the for loop to reserve one spot for the null terminator—this stops us from writing past the end of the array.
  • Initialization: oldArray starts as an empty string so the first line will always be printed (since it can’t match an empty string).
  • EOF Handling: We check if we hit EOF without reading any characters to exit the loop cleanly, avoiding infinite loops or extra empty lines.
  • String Comparison: strcmp does the heavy lifting here—if it returns a non-zero value, the lines are different, so we print the current line and update oldArray.

This program will read input (from stdin or a redirected file) and only output each line if it’s not identical to the line immediately before it, exactly what you need for filtering consecutive duplicates.

内容的提问来源于stack exchange,提问作者z.rubi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:56:31