【问题标题】:custom string alignment using printf in C在 C 中使用 printf 自定义字符串对齐
【发布时间】:2023-03-31 11:01:01
【问题描述】:

我正在尝试从给定数组中获取以下输出

 Apples      200   Grapes      900 Bananas  Out of stock
 Grapefruits 2     Blueberries 100 Orangess Coming soon
 Pears       10000

到目前为止,这是我想出的(感觉好像我做得过火了),但是,在填充列时我仍然遗漏了一些东西。我愿意接受有关如何解决此问题的任何建议。

#include <stdio.h>
#include <string.h>

#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
char *fruits[][2] = {
    {"Apples", "200"},
    {"Grapes", "900"},
    {"Bananas", "Out of stock"},
    {"Grapefruits", "2"},
    {"Blueberries", "100"},
    {"Oranges", "Coming soon"},
    {"Pears", "10000"},
};

int get_max (int j, int y) {
    int n = ARRAY_SIZE(fruits), width = 0, i;
    for (i = 0; i < n; i++) {
        if (i % j == 0 && strlen(fruits[i][y]) > width) {
            width = strlen(fruits[i][y]);
        }
    }
    return width;
}

int main(void) {
    int n = ARRAY_SIZE(fruits), i, j;
    for (i = 0, j = 1; i < n; i++) {
        if (i > 0 && i % 3 == 0) {
            printf("\n"); j++;
        }
        printf("%-*s ", get_max(j, 0), fruits[i][0]);
        printf("%-*s ", get_max(j, 1), fruits[i][1]);
    }
    printf("\n"); 
    return 0;
}

当前输出:

Apples      200          Grapes      900          Bananas     Out of stock 
Grapefruits 2            Blueberries 100          Oranges     Coming soon  
Pears       10000 

【问题讨论】:

  • 什么不起作用?当前的输出会很方便。
  • @therefromhere:当前输出已更新。

标签: c string printf


【解决方案1】:

您计算的宽度错误。本质上,您希望能够计算特定列的宽度。因此,在您的 get_max 函数中,您应该能够指定一列。然后我们可以根据它们的索引 mod 3 是否等于列从列表中挑选出元素。这可以这样完成:

int get_max (int column, int y) {
    ...
        if (i % 3 == column /* <- change */ && strlen(fruits[i][y]) > width) {
    ...
}

然后在你的主循环中,你想根据你当前所在的列来选择列的宽度。你可以通过索引 mod 3 来做到这一点:

for (i = 0, j = 1; i < n; i++) {
    ...
    printf("%-*s ", get_max(i % 3 /* change */, 0), fruits[i][0]);
    printf("%-*s ", get_max(i % 3 /* change */, 1), fruits[i][1]);
}

这应该可以如您所愿。

【讨论】:

  • 这就是我所缺少的。谢谢!
【解决方案2】:

我尝试理解您的逻辑,但我认为您可以使用带有“\t”的制表符来分隔数据:

printf("%s \t %d","banana", 200);

【讨论】:

  • 这并不总是正确对齐。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 2016-04-20
  • 2019-07-23
  • 2011-02-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多