我正在尝试从给定数组中获取以下输出
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