從標準輸入讀取列範圍對(如0 3 10 12 -1表示保留第0-3列和第10-12列),隨後逐行讀取文本,輸出原始行與篩選重組後的行。展示指針、數組、字符串處理、標準I/O的綜合應用。
#define MAX_COLS 20 // 最大列對數 #define MAX_INPUT 1000 // 最大行長 int columns[MAX_COLS]; // 存儲列範圍端點:start0, end0, start1, end1... char input[MAX_INPUT]; // 輸入緩衝區 char output[MAX_INPUT]; // 輸出緩衝區
read_column_numbersint read_column_numbers(int cols[], int max) {
int num = 0, ch;
while (num < max && scanf("%d", &cols[num]) == 1 && cols[num] >= 0)
num++;
if (num % 2 != 0) { // 必須成對
puts("Last column number is not paired.");
exit(EXIT_FAILURE);
}
while ((ch = getchar()) != EOF && ch != '\n'); // 清除行尾
return num;
}
指針洞察:cols退化為指針,&cols[num]等價cols+num,演示數組參數實為指針。
rearrangevoid rearrange(char *output, const char *input, int n_cols, const int cols[]) {
int len = strlen(input);
int out_col = 0;
for (int col = 0; col < n_cols; col += 2) {
int nchars = cols[col+1] - cols[col] + 1; // 列寬
if (cols[col] >= len || out_col == MAX_INPUT - 1) break; // 越界保護
if (out_col + nchars > MAX_INPUT - 1) // 截斷保護
nchars = MAX_INPUT - out_col - 1;
strncpy(output + out_col, input + cols[col], nchars); // 指針算術核心
out_col += nchars;
}
output[out_col] = '\0'; // 手動終止
}
| 表達式 | 等價形式 | 語義 |
|---|---|---|
input + cols[col] | &input[cols[col]] | 源字符串起始位置指針 |
output + out_col | &output[out_col] | 目標緩衝區當前寫入位置 |
strncpy(dst, src, n) | 逐字節拷貝 | 不自動添加\0,需手動終止 |