就个人而言,我会避免在输出中使用标签。如果你小心的话,你可以让对齐工作——主要是通过对每个项目使用相同的格式字符串。(您选择的变量名使得完全自动化变得更加困难;结构数组有优势。)
如果您想要对货币敏感的格式,请查看该strfmon()
函数,并记住 C 程序在 C 语言环境中运行,直到您使用
setlocale()
.
示例代码:
#include <stdio.h>
#include <locale.h>
#include <monetary.h>
int main(void)
{
double huhu = 123.45;
double haha = 234.56;
double huhu_price = 3.34;
double haha_price = 44.50;
double totalhuhu = huhu * huhu_price;
double totalhaha = haha * haha_price;
char *huhu_name = "Item A";
char *haha_name = "Much Longer Name";
setlocale(LC_ALL, "");
const char fmt[] = "%-30s %10.2f @ $%6.2f $%20.2f\n";
printf(fmt, huhu_name, huhu, huhu_price, totalhuhu);
printf(fmt, haha_name, haha, haha_price, totalhaha);
char buffer1[32];
char buffer2[32];
const char p_fmt[] = "%-30s %10.2f @ %s %s\n";
const char price[] = "%(7.2n";
const char cost[] = "%(21.2n";
strfmon(buffer1, sizeof(buffer1), price, huhu_price);
strfmon(buffer2, sizeof(buffer2), cost, totalhuhu);
printf(p_fmt, huhu_name, huhu, buffer1, buffer2);
strfmon(buffer1, sizeof(buffer1), price, haha_price);
strfmon(buffer2, sizeof(buffer2), cost, totalhaha);
printf(p_fmt, haha_name, haha, buffer1, buffer2);
return 0;
}
样本输出:
Item A 123.45 @ $ 3.34 $ 412.32
Much Longer Name 234.56 @ $ 44.50 $ 10437.92
Item A 123.45 @ $3.34 $412.32
Much Longer Name 234.56 @ $44.50 $10,437.92