本程式從標準輸入讀取資料,第一行指定欄位範圍(成對出現,負數結束),後續每行輸入依指定範圍擷取字符並輸出。例如 0 3 10 12 -1 表示輸出第 0-3 欄與第 10-12 欄內容。
read_column_numbers:讀取欄位範圍數組,驗證成對性、清除殘留換行符rearrange:處理輸入行,將指定欄位字符連接輸出main:協調讀取、處理、輸出流程#define MAX_COLS 20
#define MAX_INPUT 1000
int read_column_numbers(int columns[], int max) {
int num = 0, end_ch;
while (num < max && scanf("%d", &columns[num]) == 1 && columns[num] >= 0)
num++;
if (num % 2 != 0) { puts("Last column number is not paired."); exit(EXIT_FAILURE); }
while ((end_ch = getchar()) != EOF && end_ch != '\n'); // 清除換行
return num;
}
void rearrange(char *output, char const *input, int n_columns, int const columns[]) {
int i, len = strlen(input), out_emp_i = 0;
for (i = 0; i < n_columns; i += 2) {
int nchars = columns[i+1] - columns[i] + 1;
if (columns[i] >= len || out_emp_i == MAX_INPUT - 1) break;
if (out_emp_i + nchars > MAX_INPUT - 1)
nchars = MAX_INPUT - 1 - out_emp_i;
strncpy(output + out_emp_i, input + columns[i], nchars);
out_emp_i += nchars;
}
output[out_emp_i] = '\0';
}
columns 陣列gets)rearrange 依欄位範圍擷取字符gets 存在緩衝區溢位風險,實務建議改用 fgets此程式展示了指標運算、字串處理、輸入解析等C語言核心技巧,適合作為文字處理工具開發的基礎範例。