以下是一个简单的 C 语言程序,可以实现将不同行的同一列对齐,但最后一列除外:
```c
#include
#include
#define MAX_LINES 1000
#define MAX_COLS 100
int main() {
char lines[MAX_LINES][MAX_COLS];
int col_widths[MAX_COLS] = {0};
int num_lines = 0;
int num_cols = 0;
// Read input lines and determine column widths
while (fgets(lines[num_lines], MAX_COLS, stdin)) {
int len = strlen(lines[num_lines]);
if (len > 0 && lines[num_lines][len - 1] == '\n') {
lines[num_lines][len - 1] = '\0';
len--;
}
char *tok = strtok(lines[num_lines], " ");
int col_num = 0;
while (tok != NULL) {
int tok_len = strlen(tok);
if (tok_len > col_widths[col_num]) {
col_widths[col_num] = tok_len;
}
col_num++;
tok = strtok(NULL, " ");
}
if (col_num > num_cols) {
num_cols = col_num;
}
num_lines++;
}
// Print aligned output
for (int i = 0; i < num_lines; i++) {
char *tok = strtok(lines[i], " ");
int col_num = 0;
while (tok != NULL) {
printf("%-*s ", col_widths[col_num], tok);
col_num++;
tok = strtok(NULL, " ");
}
printf("\n");
}
return 0;
}
```
该程序首先读取输入行并确定每列的宽度,然后输出对齐的结果。在输出时,使用`%-*s`格式字符串来指定每列的宽度,并在列之间插入一个空格。最后一列不需要对齐,因此程序没有对其进行处理。