在C中使用printf自定义字符串对齐
我试图从给定的数组中获得以下输出在C中使用printf自定义字符串对齐,c,string,printf,C,String,Printf,我试图从给定的数组中获得以下输出 Apples 200 Grapes 900 Bananas Out of stock Grapefruits 2 Blueberries 100 Orangess Coming soon Pears 10000 以下是我到目前为止的想法(感觉我做得太过分了),但是,在填充列时,我仍然遗漏了一些东西。我愿意接受任何关于如何处理这个问题的建议 #include <stdio.h> #include &
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;
}
我无法理解您的逻辑,但我认为您可以使用带有“\t”的选项卡来分隔数据:
您计算宽度时出错。本质上,您希望能够计算特定列的宽度。因此,在
get_max
函数中,您应该能够指定一列。然后,我们可以根据元素的索引mod 3是否等于列,从列表中选择元素。这可以通过以下方式实现:
int get_max (int column, int y) {
...
if (i % 3 == column /* <- change */ && strlen(fruits[i][y]) > width) {
...
}
int get_max(int列,int y){
...
如果(i%3==列/*宽度){
...
}
然后,在主循环中,您希望根据当前所在的列选择列的宽度。您可以通过采用索引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]);
}
(i=0,j=1;i{
...
printf(“%-*s”,get_max(i%3/*change*/,0),fruits[i][0]);
printf(“%-*s”,get_max(i%3/*change*/,1),fruits[i][1]);
}
这应该可以像您预期的那样工作。什么不起作用?当前输出会很方便。@There from here:current output updated(当前输出已更新)。这并不总是正确对齐。这就是我缺少的。谢谢!
int get_max (int column, int y) {
...
if (i % 3 == column /* <- change */ && strlen(fruits[i][y]) > width) {
...
}
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]);
}