使用C中的printf自定义字符串对齐

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

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

这是我到目前为止所得到的(感觉我过度了),然而,当填充列时我仍然遗漏了一些东西。 我对如何解决这个问题的任何建议持开放态度。

 #include  #include  #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  width) { width = strlen(fruits[i][y]); } } return width; } int main(void) { int n = ARRAY_SIZE(fruits), i, j; for (i = 0, j = 1; 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 

你正在计算宽度错误。 实质上,您希望能够计算特定列的宽度。 因此,在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]); } 

这应该按照您的预期工作。

我尝试了解你的逻辑,但我认为你可以使用带有“\ t”的标签来分隔数据:

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