gpt4 book ai didi

arrays - 使用 printf 函数格式化间距 C

转载 作者:行者123 更新时间:2023-12-02 16:17:50 26 4
gpt4 key购买 nike

如何创建一个代码,其中 NumbersMonths 的间距彼此等距。代码源码已在issue的回答中获取.

#include <stdio.h>

#define MAX_LEN 32

int main() {
int Numbers[12] = {3, 4, 5, 1, 2, 7, 8, 9, 3, 4, 7, 8};
char Months[][MAX_LEN] = {"Jan", "Feb", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};

for (int i = 0; i < 12; i++)
printf("%s: %d\n", Months[i], Numbers[i]);

return 0;
}

输出

Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

预期输出:

Jan:       3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

最佳答案

您可以在格式字符串中使用额外的修饰符来使 printf() 正确对齐:

  • 要打印特定宽度的内容,请在格式化字符之前将宽度作为整数预先添加:例如,%10s 会将字符串打印到宽度为 10 的(最大)列,填充到留有空格。如果您的字符串超过 10 个字符,它会打印完整的字符串,但请记住这一点。所以你的具体例子:
char Months[][MAX_LEN] = {"Jan",       "Feb",     "March",    "April",
"May", "June", "July", "August",
"September", "October", "November", "December"};

for (int i = 0; i < 12; i++) {
/* Note the 10 here! */
printf("%10s: %d\n", Months[i], Numbers[i]);
}

结果

       Jan: 3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

如果你想左对齐你的字符串,你只需在整数值之前添加一个 - ,即:

printf("%-10s: %d\n", Months[i], Numbers[i]);

产生

Jan       : 3
Feb : 4
March : 5
April : 1
May : 2
June : 7
July : 8
August : 9
September : 3
October : 4
November : 7
December : 8
  • 或者,您也可以使用 *,它允许您在 printf() 调用中可变地声明要填充的长度。要使用它,你需要计算你希望填充的长度作为一个额外的参数:
int myPadWidth = 15;
/* calculate the length of Months[i] each loop and cast size_t result to int */
int lenMonths = (int)strlen(Months[i]);
/* Note the extra argument in the printf call here! */
printf("%s: %*d\n",Months[i],myPadWidth-lenMonths,Numbers[i]);

这会导致

Jan:            3
Feb: 4
March: 5
April: 1
May: 2
June: 7
July: 8
August: 9
September: 3
October: 4
November: 7
December: 8

关于arrays - 使用 printf 函数格式化间距 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66189160/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com