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'tonewArrayafter reading characters because functions likestrcmpandprintfrely on null-terminated strings to work correctly. - Buffer Overflow Prevention: We use
MAXCHARS - 1in the for loop to reserve one spot for the null terminator—this stops us from writing past the end of the array. - Initialization:
oldArraystarts 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:
strcmpdoes the heavy lifting here—if it returns a non-zero value, the lines are different, so we print the current line and updateoldArray.
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
相关产品推荐
相关产品推荐

