在 C 中使用 printf 自定义字符串对齐 [英] custom string alignment using printf in C

查看:54
本文介绍了在 C 中使用 printf 自定义字符串对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to get the following output from the given array

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

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

Here's what I came up so far (feels like I'm overdoing it), however, I'm still missing something when padding the columns. I'm open to any suggestions on how to approach this.

#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 

推荐答案

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

You are computing widths wrong. In essence, you want to be able to compute the width of a particular column. Thus, in your get_max function, you should be able to specify a column. We can then pick out the elements from the list based on whether their index mod 3 is equal to the column. This can be accomplished as such:

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

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

Then in your main loop, you want to choose the widths of the columns based on what column you are currently in. You can do that by taking the index 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]);
}

这应该如您所愿.

这篇关于在 C 中使用 printf 自定义字符串对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆