有很多行字符串, 每行字符串用空格分割, 可以包含1个或多个空格, 写一个 c语言程序, 将不同行的 同一列 对齐, 但最后一列除外

动态 未结 0 79
小小草
小小草 LV1 2023年9月23日 23:40 发表
以下是一个简单的 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`格式字符串来指定每列的宽度,并在列之间插入一个空格。最后一列不需要对齐,因此程序没有对其进行处理。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复